<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 促销操作类
 * @package  	htdocs
 * @subpackage  module
 * @author  	allen.qiang
 * @version 	1.0
 */

quanli_require('module/base/gSelectorHandler.class.php');

class promotionHandler {

    private $dbca;
	
	public function __construct( $dbca=null ) {
		if (!is_null($dbca))
			$this->dbca = $dbca;
	}
	//析构函数
	public function __destruct(){
	
	}


    /**
     * 查询订单促销活动
     * @param array $goods_array 商品数组
     * $goods_array = array(
     *      0 => array(
     *           'postID' => int 三级网购号
     *           'price' => double 商品实际销售价
     *           'goodsAmount' => int 商品数量
     *      )
     * )
     * @param int $promotionID 促销活动ID
     * @return null|array
     */
    public function searchBillPromotion( $goods_array, $promotionID=null ) {

        //查询促销活动
        if (is_null($promotionID)) {

            $search_sql = 'SELECT * FROM promotion_bill WHERE startDate <= ? AND endDate >= ? AND useFlg = 1';
            $billPromotion = $this->dbca->stmt_query( $search_sql, 'ss', date(G_DEFAULT_DATETIME_FORMAT), date(G_DEFAULT_DATETIME_FORMAT) );

        } else {

            $search_sql = 'SELECT * FROM promotion_bill WHERE promotionID = ? && startDate <= ? AND endDate >= ? AND useFlg = 1';
            $billPromotion = $this->dbca->stmt_query( $search_sql, 'iss', $promotionID, date(G_DEFAULT_DATETIME_FORMAT), date(G_DEFAULT_DATETIME_FORMAT) );

        }

        if (!$billPromotion)
            return null;

        $bill_promotion_array = array();

        //实例化商品筛选器类
        $gSelectorHandler = new gSelectorHandler( $this->dbca );

        //已满足的促销活动类型
        $meet_array = array();


        //检查促销活动
        foreach ($billPromotion as &$promotion) {

            $total_money = 0;

            $goods_amount = 0;

            //检查商品筛选器
            foreach($goods_array as &$goods) {

                //检查促销活动是否排斥其他促销活动
                if (isset($goods['repel']) && ($goods['repel'] == 1 || $promotion->repel == 1))
                    continue;

                if (!empty($promotion->selectorID) && !$gSelectorHandler->isValid($promotion->selectorID, $goods['postID']))
                    continue;

                //符合该促销活动的商品的总金额、总数量
                $total_money += $goods['price'] * $goods['goodsAmount'];
                $goods_amount += $goods['goodsAmount'];
                $goods['repel'] = $promotion->repel;
            }

            //没有符合订单促销的商品
            if ($goods_amount == 0)
                continue;

            //查询赠品
            if ($promotion->type == 3) {
                $search_sql = 'SELECT pg.*,gs.goodsMainPic,gs.salePrice,gs.marketPrice,gs.bigCategoryID,gs.midCategoryID,gs.smallCategoryID
                               FROM promotion_bill_detail pg
                               INNER JOIN goods_sale gs ON gs.postID = pg.postID
                               WHERE promotionID = ?';
                $gift_array = $this->dbca->stmt_query($search_sql, 'i', $promotion->promotionID);
                if (!$gift_array) {
                    continue;
                }
                
                $g = array(); //重新初始化
                
                foreach($gift_array as &$gift) {
                    $g[$gift->postID] = array(
                        'goodsName' => $gift->goodsName,
                        'saleAmount' => $gift->saleAmount,
                        'postID' => $gift->postID,
                        'goodsID' => $gift->goodsID,
                        'salePrice' => $gift->salePrice,
                        'marketPrice' => $gift->marketPrice,
                        'bigCategoryID' => $gift->bigCategoryID,
                        'midCategoryID' => $gift->midCategoryID,
                        'smallCategoryID' => $gift->smallCategoryID,
                        'price' => $gift->price,
                        'twoPostID' => $gift->twoPostID,
                        'product_code' => $gift->product_code,
                        'spec' => $gift->spec,
                        'img_link' => set_goods_img_link($gift->goodsMainPic),
                        'link' => set_goods_link($gift->postID),
                        'wap_link' => set_wap_goods_link($gift->postID),
                        'promotionID' => $promotion->promotionID
                    );
                }
            } else {
                $g = null;
            }


            //检查订单限额
            if ($total_money < $promotion->billMoney) {
                $bill_promotion_array['dissatisfy'][] =  array(
                    'remark'    => empty($promotion->remark) ? $promotion->title : $promotion->remark,
                    'type' => $promotion->type,
                    'startTime' => $promotion->startTime,
                    'endTime'   => $promotion->endTime,
                    'promotionID' => $promotion->promotionID,
                    'billMoney' => $promotion->billMoney,
                    'spread' => $promotion->billMoney - $total_money,
                    'gift' => $g,
                    'multiple' => 0
                );
            } else {
				
            	//筛选最大的优惠
                if (isset($meet_array[$promotion->type])) {

                    if ($meet_array[$promotion->type]['billMoney'] >= $promotion->billMoney) {
                        continue;
                    } else {
                        unset($bill_promotion_array['meet'][$meet_array[$promotion->type]['promotionID']]);
                    }

                }

                if ($promotion->type == 4) {

                    $arg_array = array(
                        'promotionID' => $promotion->promotionID
                    );
                    $coupon_array = $this->searchBillCoupon($arg_array);

                } else {
                    $coupon_array = null;
                }

                $bill_promotion_array['meet'][$promotion->promotionID] = array(
                    'remark'    => empty($promotion->remark) ? $promotion->title : $promotion->remark,
                    'type' => $promotion->type,
                    'startTime' => $promotion->startTime,
                    'endTime'   => $promotion->endTime,
                    'promotionID' => $promotion->promotionID,
                    'billMoney' => $promotion->billMoney,
                    'spread' => 0,
                    'subtractMoney' => $promotion->subtractMoney,
                    'gift' => $g,
                    'coupon' => $coupon_array,
                    'multiple' => floor($total_money / $promotion->billMoney),
                    'bill_status' => $promotion->bill_status
                );

                $meet_array[$promotion->type] = array(
                    'promotionID' => $promotion->promotionID,
                    'billMoney' => $promotion->billMoney
                );

            }

        }

        return $bill_promotion_array;

    }

    /**
     * 查询订单发放优惠券活动的优惠券信息
     * @param $arg_array
     * @return array|null
     */
    public function searchBillCoupon( $arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //订单促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //优惠券ID
        if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
            $sql .= ' AND couponID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponID'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_bill_coupon ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'promotionID' => $item->promotionID,
                    'couponID' => $item->couponID,
                    'couponName' => $item->couponName,
                    'couponNum' => $item->couponNum,
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }



    /**
     * 检查商品符合的订单促销活动
     * @param array $arg_array 参数数组
     * $arg_array = array (
     *      'postID' => int,  三级网购号
     * )
     * @return array|null
     */
    public function checkGoodsForBillPromotion( $arg_array ){

        //查询促销活动
        $search_sql = 'SELECT * FROM promotion_bill WHERE startDate <= ? AND endDate >= ? AND useFlg = 1 ORDER BY priority DESC ';

        $billPromotion = $this->dbca->stmt_query($search_sql, 'ss', date(G_DEFAULT_DATETIME_FORMAT), date(G_DEFAULT_DATETIME_FORMAT));

        if (!$billPromotion)
            return null;

        //促销活动数组
        $promotion_array = array();

        $repel = 0;

        //实例化商品筛选器类
        $gSelectorHandler = new gSelectorHandler( $this->dbca );

        //检查促销活动
        foreach ($billPromotion as &$promotion) {

            //检查商品筛选器
            if (!empty($promotion->selectorID) && !$gSelectorHandler->isValid($promotion->selectorID, $arg_array['postID']))
                continue;

            if (!empty($promotion_array) && ($repel == 1 || $promotion->repel == 1))
                continue;

            if ($promotion->repel == 1)
                $repel = 1;

            $promotion_array[] = array(
                'remark'    => empty($promotion->remark) ? $promotion->title : $promotion->remark,
                'type' => $promotion->type,
                'startTime' => $promotion->startTime,
                'endTime'   => $promotion->endTime,
                'promotionID' => $promotion->promotionID
            );

            if ($repel == 1)
                break;

        }

        return $promotion_array;

    }


    /**
     * 检查单个商品的促销活动
     * @param array $arg_array 参数数组
     * $arg_array = array (
     *      'product_code' => string,  商品编号
     *      'date' => string,
     * )
     * @return array|null
     */
    public function searchGoodsPromotion( $arg_array ){

        //查询促销活动
        $search_sql = 'SELECT * FROM promotion_goods WHERE startDate <= ? AND endDate >= ? AND useFlg = 1 ORDER BY priority DESC ';

        $goodsPromotion = $this->dbca->stmt_query($search_sql, 'ss', date(G_DEFAULT_DATETIME_FORMAT), date(G_DEFAULT_DATETIME_FORMAT));

        if (!$goodsPromotion)
            return null;

        //促销活动数组
        $promotion_array = array();

        $repel = 0;

        //实例化商品筛选器类
        $gSelectorHandler = new gSelectorHandler( $this->dbca );

        //检查促销活动
        foreach ($goodsPromotion as &$promotion) {

            //检查商品筛选器
            if (!empty($promotion->selectorID) && !$gSelectorHandler->isValid($promotion->selectorID, $arg_array['postID']))
                continue;

            if (!empty($promotion_array) && ($repel == 1 || $promotion->repel == 1))
                continue;

            if ($promotion->repel == 1)
                $repel = 1;

            //查询赠品
            if ($promotion->type == 5) {
                $search_sql = 'SELECT pg.*,gs.goodsMainPic FROM promotion_goods_detail pg
                               INNER JOIN goods_sale gs ON gs.postID = pg.postID
                               WHERE promotionID = ?';
                $gift_array = $this->dbca->stmt_query($search_sql, 'i', $promotion->promotionID);
                if (!$gift_array) {
                    continue;
                }
                
                $g = array(); //重新初始化
                
                foreach($gift_array as &$gift) {
                    $g[] = array(
                        'goodsName' => $gift->goodsName,
                        'saleAmount' => $gift->saleAmount,
                        'postID' => $gift->postID,
                        'goodsID' => $gift->goodsID,
                        'salePrice' => $gift->salePrice,
                        'twoPostID' => $gift->twoPostID,
                        'product_code' => $gift->product_code,
                        'spec' => $gift->spec,
                        'link' => set_goods_link( $gift->postID ),
                        'img_link' => set_goods_img_link( $gift->goodsMainPic ),
                    );
                }
            } else {
                $g = null;
            }

            $promotion_array[] = array(
                'remark'    => empty($promotion->remark) ? $promotion->title : $promotion->remark,
                'money'    =>  $promotion->subtractMoney,
                'type'      => $promotion->type,
                'points'    => $promotion->points,
                'startTime' => $promotion->startTime,
                'endTime'   => $promotion->endTime,
                'promotionID' => $promotion->promotionID,
                'gift'      => $g
            );

            if ($repel == 1)
                break;

        }

        return $promotion_array;

    }
	

	/* 
	 * @abstract			searchGroup() 查询全部套装
	 *  */

	public function searchGroup ($importData = array()) {
		$return_data = array();
			
		$error_msg = '';
			
		/* 传入数据有效性验证start */
		if (isset($importData['page']) && !empty($importData['page']) && !is_numeric($importData['page'])){
			$error_msg .= '当前页码必须为数字<br/>';
		}
			
		if (isset($importData['rp']) && !empty($importData['rp']) && !is_numeric($importData['rp'])){
			$error_msg .= '每页记录数必须为数字<br/>';
		}
			
		if (isset($importData['sortname']) && !empty($importData['sortname']) && !is_string($importData['sortname'])){
			$error_msg .= '排序方式必须为字符串<br/>';
		}
			
		if (isset($importData['sortorder']) && !empty($importData['sortorder']) && !is_string($importData['sortorder'])){
			$error_msg .= '排序方式必须为字符串<br/>';
		}
			
		if (isset($importData['goods_group_name']) && !empty($importData['goods_group_name']) && !is_string($importData['goods_group_name'])){
			$error_msg .= 'goods_group_name必须为字符串<br/>';
		}
		
		if (isset($importData['date']) && !empty($importData['date']) && !is_string($importData['date'])){
			$error_msg .= 'date必须为字符串<br/>';
		}
		
		if (!empty($error_msg)){
		
			$return_data['code'] = 400;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = $error_msg;
			return $return_data;
		}
		/* 传入数据有效性验证end */
			
		$page = isset($importData['page']) ? trim($importData['page']) : null;//当前页
		$rp = isset($importData['rp']) ? trim($importData['rp']) : null;//每页记录数
		$sortname = isset($importData['sortname']) ? trim($importData['sortname']) : null;//排序字段名
		$sortorder = isset($importData['sortorder']) ? trim($importData['sortorder']) : null;//排序方式（asc,desc）
		$goods_group_name = !empty($importData['goods_group_name']) ? trim($importData['goods_group_name']) : null;//套装名称
		$date = !empty($importData['date']) ? trim($importData['date']) : null;//活动日期
		
		//求总记录数
		$sql_count = 'SELECT COUNT(goods_group_id) countNum FROM promotion_group';
		
		//
		$sql_search = 'SELECT * FROM promotion_group';
		
		//排序
		$str_order = '';
			
		//分页
		$str_limit = '';
			
		//查询条件
		$str_search = ' WHERE';
			
		//查询参数类型
		$type_search = '';
			
		//查询参数数组
		$param_search = array();
		
		//商品名称
		if (!empty($goods_group_name)){
			$str_search .= ' AND goods_group_name LIKE ?';
			$type_search .= 's';
			$param_search[] = '%'.$goods_group_name.'%';
		}
		
		//活动有效期
		if (!empty($date)){
			$str_search .= ' AND (startDate <= ? AND endDate >= ?)';
			$type_search .= 'ss';
			$param_search[] = $date;
			$param_search[] = $date;
		}
			
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
			
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
			
	//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_count = $sql_count.$str_search;
			$sql_search = $sql_search.$str_search.$str_order.$str_limit;
		}else {
			$sql_search = $sql_search.$str_order.$str_limit;
		}
			
		$value_count = empty($type_search) ? $this->dbca->stmt_query($sql_count) : $this->dbca->stmt_query($sql_count,$type_search,$param_search);
			
		if ($value_count){
		
			$return_data['code'] = 200;
		
			//总记录条数
			$return_data['message']['total'] = $value_count[0]->countNum;
		
			//得到查询结果
			$return_data['message']['data'] = empty($type_search) ? $this->dbca->stmt_query($sql_search) : $this->dbca->stmt_query($sql_search,$type_search,$param_search);
		
		}else {
			$return_data['code'] = 200;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = '';
		}
			
		return $return_data;
	}
	
	/**
	 * 查询商品促销列表
	 *
	 * @param unknown_type $arg_array
	 */
	public function promotionGoodsList( &$arg_array ){
		//sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动标题
        if (isset($arg_array['title']) && trim($arg_array['title']) != '') {
            $sql .= ' AND title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['title']) . '%';
        }

        //促销类型
        if (isset($arg_array['type']) && in_array($arg_array['type'], array(1 ,2 ,3, 4 , 5 , 6))) {
            $sql .= ' AND type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['type'];
        }

	    //促销日期
        if (isset($arg_array['startDate']) && trim($arg_array['startDate']) != '') {
            $sql .= ' AND DATE(startTime) <=? AND DATE(endTime) >=?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] ;
            $params_array[] = $arg_array['startDate'] ;
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql = 'SELECT COUNT(*) AS count FROM promotion_goods WHERE 1=1 ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT * FROM promotion_goods WHERE 1=1 ' . $sql;;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
                
            return $temp_item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	

	/**
	 * 删除商品促销
	 *
	 */
	public function deletePromotionGoods ( $arg_array ) {
		//商品促销号串检查
		if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );
            
		//商品促销号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);
 
        if (empty($delete_array))
            return array( 'code' => 400, 'message' => '请选择要删除的商品促销' );
       
        try {
			//循环删除商品促销
            foreach( $delete_array as &$p_l ) {
                if (!is_numeric( $p_l ))
                	throw new Exception('参数错误' , 400); 

                //查询商品促销信息
                $promotion_goods = new entity('promotion_goods');
                $promotion_goods->promotionID = $p_l ;
                if ($this->dbca->fetch( $promotion_goods ))
                    $this->dbca->delete( $promotion_goods );
                    
                //删除促销详情信息  
                $this->dbca->stmt_query('DELETE FROM promotion_goods_detail WHERE promotionID=?' ,'i' , $p_l) ;
            }
            
            return array( 'code' => 200, 'message' => '删除成功' );
        } catch (Exception $e) {
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
	}

	/**
	 *商品促销的使用和禁用
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function promotionGoodsStatus ( $arg_array ) {
		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        $str_array = explode('_', $arg_array['useFlg_str']);
        try{
	        //检查商品促销是否存在或已经被操作
	        $promotionGoods = new entity('promotion_goods');
	        $promotionGoods->promotionID = $str_array[0] ;
	        if (!$this->dbca->fetch( $promotionGoods ))
	        	throw new Exception(sprintf('促销号「%d」,的商品促销不存在,请审核后再操作',$str_array[0]) , 400) ;
	        	
	        //检查商品促销状态是否已经被修改	
			if($promotionGoods->useFlg == $str_array[1] && $str_array[1] == 1)
				throw new Exception(sprintf('促销号「%d」,的商品促销已启用',$str_array[0]) , 400) ;
				
			if($promotionGoods->useFlg == $str_array[1] && $str_array[1] == 0)
				throw new Exception(sprintf('促销号「%d」,的商品促销已禁用',$str_array[0]) , 400) ;
				
			//保存和更新商品促销 	
	     	$promotionGoods->useFlg = $str_array[1] ; 
	     	$this->dbca->save( $promotionGoods , 'promotion' );  
	     	
        }catch (Exception $e) {
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
        
		if($str_array[1] == 1)
            return array( 'code' => 200, 'message' => '商品促销启用成功' );
            
		else if ($str_array[1] == 0)
			return array( 'code' => 200, 'message' => '商品促销禁用成功' );
	}

	/**
	 * 保存商品促销
	 *
	 * @param unknown_type $arg_array
	 */
	public function savePromotionGoodsInfo( $arg_array ){
		//参数检查
		if(!isset($arg_array['type'] ,$arg_array['promotionID'] ,$arg_array['title'], $arg_array['startTime'] ,$arg_array['creator'] , $arg_array['endTime'] ,$arg_array['description']))
			return array( 'code' => 400, 'message' => '缺少参数' );
		
		$type  	   	 = $arg_array['type'] ;
		$title 	   	 = htmlspecialchars(trim($arg_array['title'])) ;
		$startTime 	 = $arg_array['startTime'] ;
		$endTime   	 = $arg_array['endTime'] ;
		$priority  	 = $arg_array['priority'] ;
		//$repel     	 = $arg_array['repel'] ;
		$useFlg    	 = $arg_array['useFlg'] ;
		$description = htmlspecialchars(trim($arg_array['description'])) ;
		$promotionID = $arg_array['promotionID'] ;
		
		$subtractMoney = 0 ;		//立减金额
		$points		   = 0 ;		//积分倍数
		$selectorID	   = 0 ; 		//商品筛选器
		$goodsArray	   = array() ;  //商品明细
		
		//规则参数查检
		$error_msg = '' ;
		if(!in_array($type , array(1,2,3,4,5)))
			$error_msg .= '商品促销类型参数错误</br>'; 
			
		if($title == '')
			$error_msg .= '促销活动标题不能为空</br>' ;
			
		if($startTime == '' || $endTime == '')
			$error_msg .= '促销开始和结束时间不能为空</br>' ;
		
		if($type == 1){
			if(!isset($arg_array['concessions_' . $type] , $arg_array['selectorID_' . $type] ))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			//立减规则参数 	
			$selectorID    = $arg_array['selectorID_' . $type] ;
			$subtractMoney = $arg_array['concessions_' . $type] ;
		}elseif( $type == 2 ){
			if(!isset($arg_array['concessions_' . $type] , $arg_array['selectorID_' . $type] ))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			//特价规则参数	
			$subtractMoney = $arg_array['concessions_' . $type] ;	
			$selectorID  = $arg_array['selectorID_' . $type] ;
		}elseif( $type == 3 ){
			if(!isset( $arg_array['selectorID_' . $type]))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			//免邮费规则参数		
			$selectorID  = $arg_array['selectorID_' . $type] ;

		}elseif( $type == 4 ){
			if(!isset( $arg_array['concessions_' . $type] , $arg_array['selectorID_' . $type] ))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			//送积分规则参数	
			$points		= $arg_array['concessions_' . $type] ;	
			$selectorID = $arg_array['selectorID_' . $type] ;	
				
		}elseif( $type == 5 ){
			if(!isset( $arg_array['selectorID_' . $type]))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			if(!isset($arg_array['goods']) || empty($arg_array['goods']) )	
				return array( 'code' => 400, 'message' => '赠品明细不能为空' );
				
			//商品赠品规则参数		
			$selectorID  = $arg_array['selectorID_' . $type] ;		
			
			//商品明细
			$goodsArray = $arg_array['goods'] ;
			
		}
		
		try{
			if($promotionID != ""){
				//检查活动优先级是否被使用
				$issetPriority = $this->dbca->stmt_query('SELECT COUNT(*) count FROM promotion_goods WHERE promotionID!=? AND priority=?','ii',$promotionID,$priority) ;
				if( $issetPriority[0]->count > 0 )
					throw new Exception('促销优先级已经被使用' , 400) ;
				
				//检查商品明细 
				$promotion_goods = array() ;
				if($goodsArray) {
					foreach ($goodsArray as &$g_l) {
						$goodsInfo = new entity('goods_sale') ;
						$goodsInfo->postID = $g_l[1] ;
						if(!$this->dbca->fetch($goodsInfo))
							throw new Exception(sprintf('SKU「%s」的商品不存在' ,$g_l[0]), 400) ;
							
						//查询商品是否下架
						if($goodsInfo->useFlg == 0 || $goodsInfo->forsale == 0)
							throw new Exception(sprintf('SKU「%s」的商品已经下架' ,$g_l[0]), 400) ;
						
						//商品促销明细	
						$goods_detail = new entity('promotion_goods_detail') ;
						$goods_detail->promotionID = $promotionID ;
						$goods_detail->creator 	   = $arg_array['creator']  ;
						$goods_detail->postID 	   = $g_l[1] ;
						$goods_detail->goodsID 	   = $goodsInfo->goodsID ;
						$goods_detail->goodsName   = $goodsInfo->goodsName ;
						$goods_detail->salePrice   = $goodsInfo->salePrice ;
						$goods_detail->saleAmount  = $g_l[2]  ;
						$goods_detail->twoPostID   = $goodsInfo->twoPostID ;
						$goods_detail->product_code= $g_l[0]  ;
						$goods_detail->spec		   = $goodsInfo->spec ;
						$promotion_goods[] = $goods_detail ;
					}
				}	

					
				//保存促销信息
				$save_promotion_goods = new entity('promotion_goods') ;
				$save_promotion_goods->promotionID 	 = $promotionID ;
				if(!$this->dbca->fetch($save_promotion_goods))
					throw new Exception(sprintf('促销活动号「%s」的促销不存在' ,$promotionID), 400) ;
				
				$save_promotion_goods->editor    	 = $arg_array['creator'] ;
				$save_promotion_goods->title   	  	 = $arg_array['title'] ;
				$save_promotion_goods->startDate  	 = $arg_array['startTime'] ;
				$save_promotion_goods->endDate	  	 = $arg_array['endTime'] ;
				$save_promotion_goods->type		  	 = $type ;
				
				$save_promotion_goods->selectorID 	 = $selectorID ;
				$save_promotion_goods->subtractMoney = $subtractMoney ;
				$save_promotion_goods->points		 = $points ;
				$save_promotion_goods->priority		 = $priority;
				$save_promotion_goods->remark		 = $description;
				//$save_promotion_goods->repel		 = $repel;
				$save_promotion_goods->useFlg		 = $useFlg;
				$this->dbca->save($save_promotion_goods , 'promotion' );
				
				//删除老的促销详情
				$this->dbca->stmt_query('DELETE FROM promotion_goods_detail WHERE promotionID=?' , 'i' , $promotionID);
				
				//保存商品促销明细
				if($promotion_goods) {
					foreach ($promotion_goods as &$p_l) {
						$this->dbca->save($p_l , 'promotion' ) ;
					}
				}
			
				return array( 'code' => 200, 'message' => '商品促销更新成功' );
			}else{
				//生成商品促销活动号
				$promotionID = $this->promotion_seq_no() ;
			
				//检查活动优先级是否被使用
				$priorityInfo = new entity('promotion_goods') ;
				$priorityInfo->priority = $priority ;
				if($this->dbca->fetch($priorityInfo))
					throw new Exception('促销优先级已经被使用' , 400) ;
				
				//检查商品明细 
				$promotion_goods = array() ;
				if($goodsArray) {
					foreach ($goodsArray as &$g_l) {
						$goodsInfo = new entity('goods_sale') ;
						$goodsInfo->postID = $g_l[1] ;
						if(!$this->dbca->fetch($goodsInfo))
							throw new Exception(sprintf('SKU「%s」的商品不存在' ,$g_l[0]), 400) ;
							
						//查询商品是否下架
						if($goodsInfo->useFlg == 0 || $goodsInfo->forsale == 0)
							throw new Exception(sprintf('SKU「%s」的商品已经下架' ,$g_l[0]), 400) ;
						
						//商品促销明细	
						$goods_detail = new entity('promotion_goods_detail') ;
						$goods_detail->promotionID = $promotionID ;
						$goods_detail->creator 	   = $arg_array['creator']  ;
						$goods_detail->postID 	   = $g_l[1] ;
						$goods_detail->goodsID 	   = $goodsInfo->goodsID ;
						$goods_detail->goodsName   = $goodsInfo->goodsName ;
						$goods_detail->salePrice   = $goodsInfo->salePrice ;
						$goods_detail->saleAmount  = $g_l[2]  ;
						$goods_detail->twoPostID   = $goodsInfo->twoPostID ;
						$goods_detail->product_code= $g_l[0]  ;
						$goods_detail->spec		   = $goodsInfo->spec ;
						$promotion_goods[] = $goods_detail ;
					}
				}	

				//保存促销信息
				$save_promotion_goods = new entity('promotion_goods') ;
				$save_promotion_goods->creator    	 = $arg_array['creator'] ;
				$save_promotion_goods->title   	  	 = $arg_array['title'] ;
				$save_promotion_goods->startDate  	 = $arg_array['startTime'] ;
				$save_promotion_goods->endDate	  	 = $arg_array['endTime'] ;
				$save_promotion_goods->type		  	 = $type ;
				$save_promotion_goods->promotionID 	 = $promotionID ;
				$save_promotion_goods->selectorID 	 = $selectorID ;
				$save_promotion_goods->subtractMoney = $subtractMoney ;
				$save_promotion_goods->points		 = $points ;
				$save_promotion_goods->priority		 = $priority;
				//$save_promotion_goods->repel		 = $repel;
				$save_promotion_goods->remark		 = $description;
				$save_promotion_goods->useFlg		 = $useFlg;
				$this->dbca->save($save_promotion_goods , 'promotion' );
				
				//保存商品促销明细
				if($promotion_goods) {
					foreach ($promotion_goods as &$p_l) {
						$this->dbca->save($p_l , 'promotion' ) ;
					}
				}
				
				return array( 'code' => 200, 'message' => '商品促销保存成功' );
			}
			
		}catch (Exception $e) {
			if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
		}

	}

	/**
	 * 商品促销号
	 *
	 * @return unknown
	 */
	public function promotion_seq_no(){
		
		$this->dbca->stmt_query('UPDATE promotion_seqno SET seqno=LAST_INSERT_ID(seqno+1)');
		if ($r =& $this->dbca->stmt_query('SELECT LAST_INSERT_ID() seq_no')){
			$promotionID = $r[0]->seq_no;
			return $promotionID ;
		}
		
		return null ;	
	}
	
	/**
	 * 查询订单促销列表
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function promotionBillList( &$arg_array ){
		//sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动标题
        if (isset($arg_array['title']) && trim($arg_array['title']) != '') {
            $sql .= ' AND title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['title']) . '%';
        }

        //促销类型
        if (isset($arg_array['type']) && in_array($arg_array['type'], array(1 ,2 ,3, 4 , 5 , 6))) {
            $sql .= ' AND type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['type'];
        }

	    //促销日期
        if (isset($arg_array['startDate']) && trim($arg_array['startDate']) != '') {
            $sql .= ' AND DATE(startTime) <=? AND DATE(endTime) >=?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] ;
            $params_array[] = $arg_array['startDate'] ;
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql = 'SELECT COUNT(*) AS count FROM promotion_bill WHERE 1=1 ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT * FROM promotion_bill WHERE 1=1 ' . $sql;;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
                
            return $temp_item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	
	/**
	 * 删除订单促销
	 *
	 */
	public function deletePromotionBill ( $arg_array ) {
		//订单促销号串检查
		if (!isset($arg_array['delete_str']))
            return array( 'code' => 400, 'message' => '缺少参数' );
            
		//订单促销号串截成数组
        $delete_array = explode('_', $arg_array['delete_str']);
 
        if (empty($delete_array))
            return array( 'code' => 400, 'message' => '请选择要删除的订单促销' );
       
        try {
			//循环删除订单促销
            foreach( $delete_array as &$p_l ) {
                if (!is_numeric( $p_l ))
                	throw new Exception('参数错误' , 400); 

                //查询订单促销信息
                $promotionBill = new entity('promotion_bill');
                $promotionBill->promotionID = $p_l ;
                if ($this->dbca->fetch( $promotionBill ))
                    $this->dbca->delete( $promotionBill );
                    
                //删除促销详情信息  
                $this->dbca->stmt_query('DELETE FROM promotion_bill_detail WHERE promotionID=?' ,'i' , $p_l) ;
                
                //删除优惠券详情信息
                $this->dbca->stmt_query('DELETE FROM promotion_bill_coupon WHERE promotionID=?' ,'i' , $p_l) ;
            }
            
            return array( 'code' => 200, 'message' => '删除成功' );
        } catch (Exception $e) {
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
	}
	
	/**
	 *订单促销的使用和禁用
	 *
	 * @param unknown_type $arg_array
	 * @return unknown
	 */
	public function promotionBillStatus ( $arg_array ) {
		//参数检查
		if (!isset($arg_array['useFlg_str']) || $arg_array['useFlg_str'] == '')
            return array( 'code' => 400, 'message' => '缺少参数' );

        $str_array = explode('_', $arg_array['useFlg_str']);
        try{
	        //检查订单促销是否存在或已经被操作
	        $promotionBill = new entity('promotion_bill');
	        $promotionBill->promotionID = $str_array[0] ;
	        if (!$this->dbca->fetch( $promotionBill ))
	        	throw new Exception(sprintf('促销号「%d」,的订单促销不存在,请审核后再操作',$str_array[0]) , 400) ;
	        	
	        //检查订单促销状态是否已经被修改	
			if($promotionBill->useFlg == $str_array[1] && $str_array[1] == 1)
				throw new Exception(sprintf('促销号「%d」,的订单促销已启用',$str_array[0]) , 400) ;
				
			if($promotionBill->useFlg == $str_array[1] && $str_array[1] == 0)
				throw new Exception(sprintf('促销号「%d」,的订单促销已禁用',$str_array[0]) , 400) ;
				
			//保存和更新订单促销 	
	     	$promotionBill->useFlg = $str_array[1] ; 
	     	$this->dbca->save( $promotionBill , 'promotion' );  
	     	
	     	if($str_array[1] == 1)
	            return array( 'code' => 200, 'message' => '订单促销启用成功' );
	            
			else if ($str_array[1] == 0)
				return array( 'code' => 200, 'message' => '订单促销禁用成功' );

        }catch (Exception $e) {
            if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
        }
      
	}
	
	/**
	 * 保存订单促销
	 *
	 * @param unknown_type $arg_array
	 */
	public function savePromotionBillInfo( $arg_array ){
		//参数检查
		if(!isset($arg_array['type'] ,$arg_array['promotionID'] ,$arg_array['billAmount'],$arg_array['title'], $arg_array['startTime'] ,$arg_array['creator'] , $arg_array['endTime'] ,$arg_array['description']))
			return array( 'code' => 400, 'message' => '缺少参数' );
		
		$type  	   	 = $arg_array['type'] ;
		$title 	   	 = htmlspecialchars(trim($arg_array['title'])) ;
		$startTime 	 = $arg_array['startTime'] ;
		$endTime   	 = $arg_array['endTime'] ;
		//$priority  	 = $arg_array['priority'] ;
		//$repel     	 = $arg_array['repel'] ;
		$useFlg    	 = $arg_array['useFlg'] ;
		$description = htmlspecialchars(trim($arg_array['description'])) ;
		$promotionID = $arg_array['promotionID'] ;
		$billAmount	 = $arg_array['billAmount'] ;
		
		$subtractMoney = 0 ;		//立减金额
		$selectorID	   = 0 ; 		//商品筛选器
		$couponArray   = array();	//优惠券明细
		$goodsArray	   = array() ;  //商品明细
		$bill_status   = 0 ;
		
		//规则参数查检
		$error_msg = '' ;
		if(!in_array($type , array(1,2,3,4,5)))
			$error_msg .= '商品促销类型参数错误</br>'; 
			
		if($title == '')
			$error_msg .= '促销活动标题不能为空</br>' ;
			
		if($startTime == '' || $endTime == '')
			$error_msg .= '促销开始和结束时间不能为空</br>' ;
			
		/*if(!is_numeric($priority))
			$error_msg .= '促销优先级必须为数字</br>' ;*/
		
		if($type == 1){
			if(!isset($arg_array['concessions_' . $type] , $arg_array['selectorID_' . $type]  ))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			//立减规则参数 	
			$selectorID    = $arg_array['selectorID_' . $type] ;
			$subtractMoney = $arg_array['concessions_' . $type] ;

		}elseif( $type == 2 ){
			if(!isset( $arg_array['selectorID_' . $type] ))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			//特价规则参数	
			$selectorID  = $arg_array['selectorID_' . $type] ;
		}elseif( $type == 4 ){
			if(!isset( $arg_array['selectorID_' . $type] ,$arg_array['couponLine'] ,$arg_array['bill_status']))
				return array( 'code' => 400, 'message' => '缺少参数' );
				
			//送优惠券规则参数	
			$selectorID   = $arg_array['selectorID_' . $type] ;	
			$couponArray  = $arg_array['couponLine'];				//优惠券明细
			$bill_status  = $arg_array['bill_status'] ;
				
		}elseif( $type == 3 ){
			if(!isset( $arg_array['selectorID_' . $type]))
				return array( 'code' => 400, 'message' => '缺少参数' );
			
			if(!isset($arg_array['goods']) || empty($arg_array['goods']) )	
				return array( 'code' => 400, 'message' => '赠品明细不能为空' );	
				
			$selectorID  = $arg_array['selectorID_' . $type] ;					//商品赠品规则参数	
			$goodsArray  = $arg_array['goods'] ;								//商品明细
		}
		
		$this->dbca->beginTransaction() ;
		try{
			if($promotionID != ""){
				/*//检查活动优先级是否被使用
				$issetPriority = $this->dbca->stmt_query('SELECT COUNT(*) count FROM promotion_bill WHERE promotionID!=? AND priority=?','ii',$promotionID,$priority) ;
				if( $issetPriority[0]->count > 0 )
					throw new Exception('促销优先级已经被使用' , 400) ;*/
				
				//检查商品明细 
				$promotion_goods = array() ;
				if($goodsArray) {
					foreach ($goodsArray as &$g_l) {
						$goodsInfo = new entity('goods_sale') ;
						$goodsInfo->postID = $g_l[1] ;
						if(!$this->dbca->fetch($goodsInfo))
							throw new Exception(sprintf('商品SKU「%s」的商品不存在' ,$g_l[0]), 400) ;
							
						//查询商品是否下架
						if($goodsInfo->useFlg == 0 || $goodsInfo->forsale == 0)
							throw new Exception(sprintf('商品SKU「%s」的商品已经下架' ,$g_l[0]), 400) ;
						
						//商品促销明细	
						$goods_detail = new entity('promotion_bill_detail') ;
						$goods_detail->promotionID = $promotionID ;
						$goods_detail->creator 	   = $arg_array['creator']  ;
						$goods_detail->postID 	   = $g_l[1] ;
						$goods_detail->goodsID 	   = $goodsInfo->goodsID ;
						$goods_detail->goodsName   = $goodsInfo->goodsName ;
						$goods_detail->price   	   = $g_l[3] ;
						$goods_detail->saleAmount  = $g_l[2]  ;
						$goods_detail->twoPostID   = $goodsInfo->twoPostID ;
						$goods_detail->product_code= $g_l[0]  ;
						$goods_detail->spec		   = $goodsInfo->spec ;
						$promotion_goods[] = $goods_detail ;
					}
				}	
				
				//检查优惠券明细
				$promotion_coupon = array();
				if($couponArray){
					foreach ($couponArray as $couponVal){
						//检查优惠券数量是否正确
						if(!is_numeric($couponVal[0]) || intval($couponVal[0]) <=0)
							throw new Exception('优惠券的张数必须为正整数', 400) ;
							
						if(!is_numeric($couponVal[1]) || intval($couponVal[1]) <=0)
							throw new Exception('优惠券的编号必须为正整数', 400) ;
							
						$accountCoupon = new entity('promotion_coupon');
						$accountCoupon->couponID = $couponVal[1];
						if(!$this->dbca->fetch($accountCoupon))
							throw new Exception(sprintf('优惠券「%s」信息不存在' , $couponVal[1]), 400) ;
							
						$coupon_detail = new entity('promotion_bill_coupon');
						$coupon_detail->creator     = $arg_array['creator'];
						$coupon_detail->promotionID = $promotionID;
						$coupon_detail->couponID    = $couponVal[1];
						$coupon_detail->couponNum   = $couponVal[0];
						$coupon_detail->couponName  = $accountCoupon->couponName ;
						$promotion_coupon[] = $coupon_detail;
					}
				}
					
				//保存促销信息
				$save_promotion_bill = new entity('promotion_bill') ;
				$save_promotion_bill->promotionID 	 = $promotionID ;
				if(!$this->dbca->fetch($save_promotion_bill))
					throw new Exception(sprintf('促销活动号「%s」的促销不存在' ,$promotionID), 400) ;
				
				$save_promotion_bill->editor    	 = $arg_array['creator'] ;
				$save_promotion_bill->title   	  	 = $arg_array['title'] ;
				$save_promotion_bill->startDate  	 = $arg_array['startTime'] ;
				$save_promotion_bill->endDate	  	 = $arg_array['endTime'] ;
				$save_promotion_bill->type		  	 = $type ;
				$save_promotion_bill->selectorID 	 = $selectorID ;
				$save_promotion_bill->subtractMoney  = $subtractMoney ;
				$save_promotion_bill->billMoney	 	 = $billAmount ;
				$save_promotion_bill->bill_status	 = $bill_status ;
				$save_promotion_bill->priority		 = $promotionID;
				//$save_promotion_bill->repel			 = $repel;
				$save_promotion_bill->useFlg		 = $useFlg;
				$save_promotion_bill->remark		 = $description;
				$this->dbca->save($save_promotion_bill , 'promotion' );
				
				//删除老的促销详情
				$this->dbca->stmt_query('DELETE FROM promotion_bill_detail WHERE promotionID=?' , 'i' , $promotionID);
				
				//删除老的优惠券详情
				$this->dbca->stmt_query('DELETE FROM promotion_bill_coupon WHERE promotionID=?' , 'i' , $promotionID);
				
				//保存商品促销明细
				if($promotion_goods) {
					foreach ($promotion_goods as &$p_l) {
						$this->dbca->save($p_l , 'promotion' ) ;
					}
				}
				
				//保存优惠券明细
				if($promotion_coupon) {
					foreach ($promotion_coupon as &$c_l) {
						$this->dbca->save($c_l , 'promotion' ) ;
					}
				}
				
				$this->dbca->commit() ;
				return array( 'code' => 200, 'message' => '商品促销更新成功' );
			}else{
				//生成商品促销活动号
				$promotionID = $this->promotion_seq_no() ;
			
				//检查活动优先级是否被使用
				/*$priorityInfo = new entity('promotion_bill') ;
				$priorityInfo->priority = $priority ;
				if($this->dbca->fetch($priorityInfo))
					throw new Exception('促销优先级已经被使用' , 400) ;*/
				
				//检查商品明细 
				$promotion_goods = array() ;
				if($goodsArray) {
					foreach ($goodsArray as &$g_l) {
						$goodsInfo = new entity('goods_sale') ;
						$goodsInfo->postID = $g_l[1] ;
						if(!$this->dbca->fetch($goodsInfo))
							throw new Exception(sprintf('商品SKU「%s」的商品不存在' ,$g_l[0]), 400) ;
							
						//查询商品是否下架
						if($goodsInfo->useFlg == 0 || $goodsInfo->forsale == 0)
							throw new Exception(sprintf('商品SKU「%s」的商品已经下架' ,$g_l[0]), 400) ;
						
						//商品促销明细	
						$goods_detail = new entity('promotion_bill_detail') ;
						$goods_detail->promotionID = $promotionID ;
						$goods_detail->creator 	   = $arg_array['creator']  ;
						$goods_detail->postID 	   = $g_l[1] ;
						$goods_detail->goodsID 	   = $goodsInfo->goodsID ;
						$goods_detail->goodsName   = $goodsInfo->goodsName ;
						$goods_detail->price   = $g_l[3] ;
						$goods_detail->saleAmount  = $g_l[2]  ;
						$goods_detail->twoPostID   = $goodsInfo->twoPostID ;
						$goods_detail->product_code= $g_l[0]  ;
						$goods_detail->spec		   = $goodsInfo->spec ;
						$promotion_goods[] = $goods_detail ;
					}
				}	
				
				//检查优惠券明细
				$promotion_coupon = array();
				if($couponArray){
					foreach ($couponArray as $couponVal){
						//检查优惠券数量是否正确
						if(!is_numeric($couponVal[0]) || intval($couponVal[0]) <=0)
							throw new Exception('优惠券的张数必须为正整数', 400) ;
							
						if(!is_numeric($couponVal[1]) || intval($couponVal[1]) <=0)
							throw new Exception('优惠券的编号必须为正整数', 400) ;
							
						$accountCoupon = new entity('promotion_coupon');
						$accountCoupon->couponID = $couponVal[1];
						if(!$this->dbca->fetch($accountCoupon))
							throw new Exception(sprintf('优惠券「%s」信息不存在' , $couponVal[1]), 400) ;
							
						$coupon_detail = new entity('promotion_bill_coupon');
						$coupon_detail->creator     = $arg_array['creator'];
						$coupon_detail->promotionID = $promotionID;
						$coupon_detail->couponID    = $couponVal[1];
						$coupon_detail->couponNum   = $couponVal[0];
						$coupon_detail->couponName  = $accountCoupon->couponName ;
						$promotion_coupon[] = $coupon_detail;
					}
				}
	
				//保存促销信息
				$save_promotion_bill = new entity('promotion_bill') ;
				$save_promotion_bill->creator    	 = $arg_array['creator'] ;
				$save_promotion_bill->title   	  	 = $arg_array['title'] ;
				$save_promotion_bill->startDate  	 = $arg_array['startTime'] ;
				$save_promotion_bill->endDate	  	 = $arg_array['endTime'] ;
				$save_promotion_bill->type		  	 = $type ;
				$save_promotion_bill->promotionID 	 = $promotionID ;
				$save_promotion_bill->selectorID 	 = $selectorID ;
				$save_promotion_bill->subtractMoney  = $subtractMoney ;
				$save_promotion_bill->billMoney	 	 = $billAmount ;
				$save_promotion_bill->bill_status	 = $bill_status ;
				$save_promotion_bill->priority		 = $promotionID;
				//$save_promotion_bill->repel			 = $repel;
				$save_promotion_bill->remark		 = $description;
				$save_promotion_bill->useFlg		 = $useFlg;
				
				$this->dbca->save($save_promotion_bill , 'promotion' );
				
				//保存商品促销明细
				if($promotion_goods) {
					foreach ($promotion_goods as &$p_l) {
						$this->dbca->save($p_l , 'promotion' ) ;
					}
				}
				
				//保存优惠券明细
				if($promotion_coupon) {
					foreach ($promotion_coupon as &$c_l) {
						$this->dbca->save($c_l , 'promotion' ) ;
					}
				}
				
				$this->dbca->commit() ;
				return array( 'code' => 200, 'message' => '订单促销保存成功' );
			}
			
		}catch (Exception $e) {
			$this->dbca->rollBack() ;
			if ($e->getCode() > 0) 
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }
		}

	}
	
	/*
	 * @abstract       editPackage()   编辑、新增商品套装
	 * @param          $importData = array(必传：'actionFlg','sendTypeID','send_region_id(编辑必传)','send_region_name',
	 * 										   	'freight','regionArr','creator(新增必传)','editor(编辑必传)'
	 * 									       可选：'standardFlg','standard','overStandard','freeBillMoney','promotionFreight',
	 * 											'startDate','endDate')
	 * @return         $return_data=array('code','message');
	 *  */
	public function editPackage ($importData) {
		$return_data = array();
		
		$error_msg = '';
		
		/* 传入数据有效性验证start */
		//没有传入数据
		if (!isset($importData)) {
			$error_msg .= '没有传入任何数据<br/>';
		}
		
		if (empty($importData['mainInfo'])) {
			$error_msg .= '未传入主商品信息<br/>';
		}
	
		if (empty($importData['groupGoodsInfo'])) {
			$error_msg .= '未传入套装商品信息<br/>';
		}
	
		if (!isset($importData['operFlg']) || empty($importData['operFlg'])){
			$error_msg .= '未传入operFlg<br/>';
		}
		
		//operFlg：2，新增；3，修改
		if ($importData['operFlg'] != 2 && $importData['operFlg'] != 3) {
			$error_msg .= '传入operFlg错误<br/>';
		}
		
		if ($importData['operFlg'] == 2 && !isset($importData['creator'])) {
			$error_msg .= '创建人不能为空<br/>';
		}
	
		if ($importData['operFlg'] == 3 && !isset($importData['editor'])) {
			$error_msg .= '修改人不能为空<br/>';
		}
		
		if (empty($importData['mainInfo']['goods_group_name'])) {
			$error_msg .= '套装名称不能为空<br/>';
		}
	
		if (empty($importData['mainInfo']['startDate'])) {
			$error_msg .= '开始时间不能为空<br/>';
		}
	
		if (empty($importData['mainInfo']['endDate'])) {
			$error_msg .= '结束时间不能为空<br/>';
		}
	
		if ($importData['mainInfo']['endDate'] < $importData['mainInfo']['startDate']){
			$error_msg .= '开始时间不能大于结束时间<br/>';
		}
		/************************必须有其他套装商品********************************/
		if (count($importData['groupGoodsInfo']) <= 1) {
			$error_msg .= '请至少选择2件套装商品<br/>';
		}
		/************************必须有其他套装商品********************************/
		if ($importData['operFlg'] == 3 && empty($importData['mainInfo']['goods_group_id'])) {
			$error_msg .= '原套装传值错误<br/>';
		}
	
		if (!empty($error_msg)){
			$return_data['code'] = 400;
			$return_data['message'] = $error_msg;
			return $return_data;
		}
		/* 传入数据有效性验证end */
	
	
		$operFlg = $importData['operFlg'];//operFlg（2新增，3编辑）
		$creator = $importData['creator'];//创建人
		$editor = $importData['editor'];//修改人
 		$product_code = trim($importData['mainInfo']['product_code']);//主商品商品编号
		$goods_group_id = trim($importData['mainInfo']['goods_group_id']);//套装号
// 		$postID = trim($importData['mainInfo']['postID']);//主商品postID
		$flg = trim($importData['mainInfo']['flg']);//主商品flg（1邮购，2网站）
// 		$goodsName = trim($importData['mainInfo']['goodsName']);//主商品名称
		$goods_group_name = trim($importData['mainInfo']['goods_group_name']);//套装名称
		$startDate = trim($importData['mainInfo']['startDate']);//开始时间
		$endDate = trim($importData['mainInfo']['endDate']);//结束时间
		$groupGoodsInfo = $importData['groupGoodsInfo'];//套装商品（数组）
	
		/*******检测商品是否存在、在售、有库存start********/
		//检测主商品
 		$main_obj = new entity('goods_list');
 		$main_obj->product_code = $importData['mainInfo']['product_code'];
 		$main_obj->useFlg = 1;
 		$main_obj->forsale = 1;
 		if (!$this->dbca->fetch($main_obj)){
 			$return_data['code'] = 400;
 			$return_data['message'] = '主商品不存在或已下架或没有库存';
 			return $return_data;
 		}

        $goods_group_salePrice = 0; //套装商品销售价合计
		$goods_group_price = 0;//套装售价
		$goods_group_points = 0;//套装积分
	
		//检测套装商品
		//同时统计套装价和套装积分
		if (!empty($groupGoodsInfo)){

			$checkPostIDArr = array();
			
			foreach ($groupGoodsInfo as $key => $goodsList){
				
				//检测商品重复
				if (!empty($checkPostIDArr)){
					if (in_array($goodsList['product_code'], $checkPostIDArr)){
						$return_data['code'] = 400;
						$return_data['message'] = '编号['.$goodsList['product_code'].']商品有重复';
						return $return_data;
					}else {
						$checkArr[] = $goodsList['product_code'];
					}
				}
				
				$group_obj = new entity('goods_list');
				$group_obj->product_code = $goodsList['product_code'];
				$group_obj->useFlg = 1;
				$group_obj->forsale = 1;
				if (!$this->dbca->fetch($group_obj)){
					$return_data['code'] = 400;
					$return_data['message'] = '编号['.$goodsList['product_code'].']商品不存在或已下架或没有库存';
					return $return_data;
				}
				$goods_group_price += $goodsList["discountPrice"];//统计套装价
				$goods_group_points += $goodsList["salePoints"];//统计套装积分
                $goods_group_salePrice += $goodsList["salePrice"];//统计套装商品销售价
			}
		}
		/*******检测商品是否存在、在售、有库存end********/
		//返回的提示信息
		$message = ($operFlg == 2) ? '新增套装商品成功' : '修改套装商品成功';
	
		//保存到数据库
		try {
	
			//保存到promotion_group中
			$group_obj = new entity('promotion_group');
			$group_obj->goods_group_id = $goods_group_id;
			if ($this->dbca->fetch($group_obj)){
				$group_obj->editor = $editor;
			}else {
				//如果没fetch到，且operFlg==3，则弹出错误
				if ($operFlg == 3){
					throw new Exception('您的页面已过期，请刷新页面', -1000);
				}
				$group_obj->creator = $creator;
				$group_obj->useFlg = 1;//新增时默认启用
			}
// 			$group_obj->goodsName = $goodsName;
// 			$group_obj->postID = $postID;
			$group_obj->goods_group_name = $goods_group_name;
			$group_obj->goods_group_price = $goods_group_price;
			$group_obj->goods_group_points = $goods_group_points;
			$group_obj->goods_group_privilege_price = $goods_group_salePrice-$goods_group_price;
			$group_obj->startDate = $startDate;
			$group_obj->endDate = $endDate;
			//$group_obj->flg = $flg;
 			$group_obj->product_code = $product_code;
	
			$result_add = $this->dbca->save($group_obj);
	
	
			if (!empty($result_add) && $operFlg == 2){
				$goods_group_id = $this->dbca->insert_id;
			}
	
			if ($operFlg == 3){
				//修改时根据套装号先删除promotion_group_detail中对应的记录
				$sql_del = 'DELETE FROM promotion_group_detail WHERE goods_group_id = ?';
				$this->dbca->stmt_query($sql_del,'i',$goods_group_id);
			}
	
			//将传入的$groupGoodsInfo保存进promotion_group_detail中
			if (!empty($groupGoodsInfo)){
				foreach ($groupGoodsInfo as $group_item){
					$detail_obj = new entity('promotion_group_detail');
					$detail_obj->creator = $creator;
					$detail_obj->goods_group_id = $goods_group_id;
					$detail_obj->goodsID = trim($group_item["goodsID"]);
					$detail_obj->postID = trim($group_item["postID"]);
					$detail_obj->goodsCount = trim($group_item["goodsCount"]);
					$detail_obj->salePrice = trim($group_item["salePrice"]);
					$detail_obj->discountPrice = trim($group_item["discountPrice"]);
					$detail_obj->salePoints = trim($group_item["salePoints"]);
					$detail_obj->goodsName = trim($group_item["goodsName"]);
					$detail_obj->goodsType = 2;//二级商品，写死
					//$detail_obj->product_code = trim($group_item["product_code"]);
					$detail_obj->link = trim($group_item["link"]);
					$detail_obj->img_link = trim($group_item["img_link"]);
					$this->dbca->save($detail_obj,'promotion');
				}
			}
	
			$return_data = array('code'=>200, 'message'=>$message);
			return  $return_data;
		}catch (Exception $e){
			$error_msg = $e->getMessage();
			$return_data = array('code'=>500, 'message'=>$error_msg);
			return  $return_data;
		}
	}
	/*
	 * 查询套装商品详情（联表goods_list查询spec标签）
	 *  */
	public function searchGroupDetailAll ( $importData=array() ){
		//返回数组
		$return_data = array();
			
		//错误信息
		$error = '';
	
		if (isset($importData['page']) && !empty($importData['page']) && !is_numeric($importData['page'])){
			$error .= '当前页码必须为数字<br/>';
		}
	
		if (isset($importData['rp']) && !empty($importData['rp']) && !is_numeric($importData['rp'])){
			$error .= '每页记录数必须为数字<br/>';
		}
	
		if (isset($importData['sortname']) && !empty($importData['sortname']) && !is_string($importData['sortname'])){
			$error .= '排序方式必须为字符串<br/>';
		}
	
		if (isset($importData['sortorder']) && !empty($importData['sortorder']) && !is_string($importData['sortorder'])){
			$error .= '排序方式必须为字符串<br/>';
		}
	
		if (!isset($importData['goods_group_id']) || empty($importData['goods_group_id'])){
			$error .= '没有传入goods_group_id<br/>';
		}
	
		if (!empty($error)){
			$return_data['code'] = 400;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = $error;
			return $return_data;
		}
	
		$goods_group_id = trim($importData['goods_group_id']);
		$page = isset($importData['page']) ? trim($importData['page']) : '';//当前页
		$rp = isset($importData['rp']) ? trim($importData['rp']) : '';//每页记录数
		$sortname = isset($importData['sortname']) ? trim($importData['sortname']) : '';//排序字段名
		$sortorder = isset($importData['sortorder']) ? trim($importData['sortorder']) : '';//排序方式
		//求总记录数
		$sql_count = 'SELECT COUNT(pgd.uuid) countNum FROM promotion_group_detail pgd';
	
		//查询SQL语句
		$sql_search = 'SELECT pgd.*, gl.spec, gl.product_code FROM promotion_group_detail pgd LEFT JOIN goods_list gl ON pgd.postID = gl.postID';
	
		//排序
		$str_order = '';
	
		//分页
		$str_limit = '';
	
		//查询条件
		$str_search = ' WHERE';
	
		//查询参数类型
		$type_search = '';
	
		//查询参数数组
		$param_search = array();
	
		//查询条件：权限组ID
		if (!empty($goods_group_id)){
			$str_search .= ' AND pgd.goods_group_id = ?';
			$type_search .= 'i';
			$param_search[] = $goods_group_id;
		}
	
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
	
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
	
		//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_count = $sql_count.$str_search;
			$sql_search = $sql_search.$str_search.$str_order.$str_limit;
		}else {
			$sql_search = $sql_search.$str_order.$str_limit;
		}
	
		$value_count = empty($type_search) ? $this->dbca->stmt_query($sql_count) : $this->dbca->stmt_query($sql_count,$type_search,$param_search);
	
		if ($value_count){
	
			$return_data['code'] = 200;
	
			//总记录条数
			$return_data['message']['total'] = $value_count[0]->countNum;
	
			//得到查询结果
			$return_data['message']['data'] = empty($type_search) ? $this->dbca->stmt_query($sql_search) : $this->dbca->stmt_query($sql_search,$type_search,$param_search);
	
		}else {
			$return_data['code'] = 200;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = '';
		}
	
		return $return_data;
	}
	
	/*
	 * @abstract deletePackage()      删除套装
	 * @param    $groupIDArr          goods_group_id组成的数组
	 * @return   array('code','message')
	 *  */
	public function deletePackage ( $groupIDArr ){
		$error = '';
	
		if (empty($groupIDArr)){
			$error = '请至少选择一条要删除的数据<br/>';
			return array('code' => 400, 'message' => $error);
		}
	
		try {
	
			$this->dbca->beginTransaction();
				
			foreach ($groupIDArr as $goods_group_id){
	
				if (!is_numeric($goods_group_id)){
					throw new Exception('goods_group_id传值错误', -1000);
				}
	
				$group_obj = new entity('promotion_group');
	
				$group_obj->goods_group_id = $goods_group_id;
	
				if (!$this->dbca->fetch($group_obj)) {
					throw new Exception('套装号：'.$goods_group_id.'的套转不存在或已被删除', -1000);
				}
				//删除套装表中对应数据
				$this->dbca->delete($group_obj);
	
				$detail_obj = new entity('promotion_group_detail');
	
				$detail_obj->goods_group_id = $goods_group_id;
	
				if ($this->dbca->fetch($detail_obj)){
						
					//删除套装商品数据
					$sql_del = 'DELETE FROM promotion_group_detail WHERE goods_group_id = ?';
					$this->dbca->stmt_query($sql_del,'i',$goods_group_id);
				}
			}
	
			$this->dbca->commit();
				
			return array( 'code' => 200, 'message' => '删除成功' );
	
		}catch (Exception $e){
			$this->dbca->rollBack();
			$msg = $e->getMessage();
			return array( 'code' => 500, 'message' => $msg );
		}
	}
	
	/**
	 * 查询商品筛选器列表
	 * @param $arg_array 参数数组
	 * @author sunchun
	 *
	 */
	public function goodsSelectorList( &$arg_array ){

		//sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
         //选择器ID
        if (isset($arg_array['selectID']) && is_numeric($arg_array['selectID']) && intval($arg_array['selectID']) > 0) {
            $sql .= ' AND selectID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['selectID'];
        }

        //选择器名称
        if (isset($arg_array['selectName']) && trim($arg_array['selectName']) != '') {
            $sql .= ' AND selectName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['selectName']) . '%';
        }
        
        if(!empty($sql))
        	$sql = 'WHERE ' . substr($sql, 4);

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql = 'SELECT COUNT(*) AS count FROM goods_selector ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT * FROM goods_selector ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
                
            return $temp_item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	/**
	 * 删除商品筛选器或筛选规则
	 *
	 * @param array 参数数组 $arg_array
	 */
	public function deleteSelector($arg_array){
		$delete_str = isset($arg_array['delete_str']) ? trim($arg_array['delete_str']) : null;
		if(empty($delete_str))
			return array('code' => 400, 'message' => '参数错误');
			
		$deleteArray = explode('.', $delete_str);
		if($deleteArray){
			try{
				foreach ($deleteArray as $val){
					//截成数组判断是删除筛选器还是筛选规则
					$valArray = explode('_', $val);
					if(count($valArray) == 3){
						//筛选规则
						$this->dbca->stmt_query(sprintf('DELETE FROM goods_selector_detail WHERE selectID = %s AND selector = \'%s\' AND selectType = %s', $valArray[0], $valArray[1], $valArray[2]));
					}else{
						//筛选器
						$this->dbca->stmt_query(sprintf('DELETE FROM goods_selector WHERE selectID = %s', $valArray[0]));
						
						//删除筛选器对应的规则
						$this->dbca->stmt_query(sprintf('DELETE FROM goods_selector_detail WHERE selectID = %s', $valArray[0]));
					}
				}
			}catch (Exception $e){
				error_log($e->getMessage());
				return array('code' => 500, 'message' => '保存数据库失败');
			}
		}
		return array('code' => 200, 'message' => '筛选器信息已删除');
	}
	
	
	/**
	 * 查询全部超值选购
	 *
	 */
	
	public function searchSelection ($importData = array()) {
		$return_data = array();
			
		$error_msg = '';
			
		/* 传入数据有效性验证start */
		if (isset($importData['page']) && !empty($importData['page']) && !is_numeric($importData['page'])){
			$error_msg .= '当前页码必须为数字<br/>';
		}
			
		if (isset($importData['rp']) && !empty($importData['rp']) && !is_numeric($importData['rp'])){
			$error_msg .= '每页记录数必须为数字<br/>';
		}
			
		if (isset($importData['sortname']) && !empty($importData['sortname']) && !is_string($importData['sortname'])){
			$error_msg .= '排序方式必须为字符串<br/>';
		}
			
		if (isset($importData['sortorder']) && !empty($importData['sortorder']) && !is_string($importData['sortorder'])){
			$error_msg .= '排序方式必须为字符串<br/>';
		}
			
		if (isset($importData['goodsChoiceID']) && !empty($importData['goodsChoiceID']) && !is_numeric($importData['goodsChoiceID'])){
			$error_msg .= 'goodsChoiceID必须为数字<br/>';
		}
	
		if (isset($importData['goodsChoiceName']) && !empty($importData['goodsChoiceName']) && !is_string($importData['goodsChoiceName'])){
			$error_msg .= 'goodsChoiceName必须为字符串<br/>';
		}
	
		if (isset($importData['date']) && !empty($importData['date']) && !is_string($importData['date'])){
			$error_msg .= 'date必须为字符串<br/>';
		}
	
		if (isset($importData['itemName']) && !empty($importData['itemName']) && !is_string($importData['itemName'])){
			$error_msg .= 'itemName必须为字符串<br/>';
		}
	
		if (!empty($error_msg)){
	
			$return_data['code'] = 400;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = $error_msg;
			return $return_data;
		}
		/* 传入数据有效性验证end */
			
		$page = isset($importData['page']) ? trim($importData['page']) : null;//当前页
		$rp = isset($importData['rp']) ? trim($importData['rp']) : null;//每页记录数
		$sortname = isset($importData['sortname']) ? trim($importData['sortname']) : null;//排序字段名
		$sortorder = isset($importData['sortorder']) ? trim($importData['sortorder']) : null;//排序方式（asc,desc）
		$goodsChoiceID = !empty($importData['goodsChoiceID']) ? trim($importData['goodsChoiceID']) : null;//活动号
		$goodsChoiceName = !empty($importData['goodsChoiceName']) ? trim($importData['goodsChoiceName']) : null;//活动名称
		$date = !empty($importData['date']) ? trim($importData['date']) : null;//活动日期
		$itemName = !empty($importData['itemName']) ? trim($importData['itemName']) : null;//分类ID
		$useFlg = isset($importData['useFlg']) && is_numeric($importData['useFlg']) ? $importData['useFlg'] : null; //启用标志
        $choice_type = isset($importData['choice_type']) && is_numeric($importData['choice_type']) ? $importData['choice_type'] : null; //选购类型

		//求总记录数
		$sql_count = 'SELECT COUNT(ps.goodsChoiceID) countNum FROM promotion_selection ps LEFT JOIN sys_item si ON ps.itemID = si.itemID';
	
		//
		$sql_search = 'SELECT ps.*, si.itemName
				       FROM promotion_selection ps
					   LEFT JOIN sys_item si ON ps.itemID = si.itemID';
	
		//排序
		$str_order = '';
			
		//分页
		$str_limit = '';
			
		//查询条件
		$str_search = ' WHERE';
			
		//查询参数类型
		$type_search = '';
			
		//查询参数数组
		$param_search = array();
			
		//商品编号
		if (!empty($goodsChoiceID)){
			$str_search .= ' AND ps.goodsChoiceID = ?';
			$type_search .= 'i';
			$param_search[] = $goodsChoiceID;
		}
	
		//商品名称
		if (!empty($itemName)){
			$str_search .= ' AND si.itemName = ?';
			$type_search .= 's';
			$param_search[] = $itemName;
		}
		
		//商品名称
		if (!empty($goodsChoiceName)){
			$str_search .= ' AND ps.goodsChoiceName LIKE ?';
			$type_search .= 's';
			$param_search[] = '%'.$goodsChoiceName.'%';
		}
	
		//活动有效期
		if (!empty($date)){
			$str_search .= ' AND (ps.useStartDate <= ? AND ps.useEndDate >= ?)';
			$type_search .= 'ss';
			$param_search[] = $date;
			$param_search[] = $date;
		}

        //使用标志
        if (!empty($useFlg)){
            $str_search .= ' AND ps.useFlg = ?';
            $type_search .= 'i';
            $param_search[] = $useFlg;
        }

        //选购类型
        if (!empty($choice_type)){
            $str_search .= ' AND ps.choice_type = ?';
            $type_search .= 'i';
            $param_search[] = $choice_type;
        }
			
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
			
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
			
		//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_count = $sql_count.$str_search;
			$sql_search = $sql_search.$str_search.$str_order.$str_limit;
		}else {
			$sql_search = $sql_search.$str_order.$str_limit;
		}
			
		$value_count = empty($type_search) ? $this->dbca->stmt_query($sql_count) : $this->dbca->stmt_query($sql_count,$type_search,$param_search);
			
		if ($value_count){
	
			$return_data['code'] = 200;
	
			//总记录条数
			$return_data['message']['total'] = $value_count[0]->countNum;

			//得到查询结果
			$result_info = empty($type_search) ? $this->dbca->stmt_query($sql_search) : $this->dbca->stmt_query($sql_search,$type_search,$param_search);
            if($result_info){
                foreach ($result_info as $value){
                    $return_data['message']['data'][] = array(
                        'goodsChoiceID' => $value->goodsChoiceID,
                        'goodsChoiceName' => $value->goodsChoiceName,
                        'goodsChoicePrice' => $value->goodsChoicePrice,
                        'goodsCount' => $value->goodsCount,
                        'points' => $value->points,
                        'useFlg' => $value->useFlg,
                        'useStartDate' => $value->useStartDate,
                        'useEndDate' => $value->useEndDate,
                        'editor' => $value->editor,
                        'thumbpic' => $value->thumbpic,
                        'choice_type' => $value->choice_type,
                        'itemID' => $value->itemID,
                        'itemName' => $value->itemName,
                    );
                }
            }
	
		}else {
			$return_data['code'] = 200;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = '';
		}
			
		return $return_data;
	}
	
	/*
	 * @abstract       editSelection()   编辑、新增超值选购
	 * @param          $importData = array(必传：'operFlg','sendTypeID','send_region_id(编辑必传)','send_region_name',
	 * 										   	'freight','regionArr','creator(新增必传)','editor(编辑必传)'
	 * 									       可选：'standardFlg','standard','overStandard','freeBillMoney','promotionFreight',
	 * 											'startDate','endDate')
	 * @return         $return_data=array('code','message');
	 *  */
	public function editSelection ($importData) {
		$return_data = array();
	
		$error_msg = '';
	
		/* 传入数据有效性验证start */
		//没有传入数据
		if (!isset($importData)) {
			$error_msg .= '没有传入任何数据<br/>';
		}
	
		if (empty($importData['mainInfo'])) {
			$error_msg .= '未传入主商品信息<br/>';
		}
	
		if (empty($importData['selectionInfo'])) {
			$error_msg .= '未传入选购商品信息<br/>';
		}
	
		if (!isset($importData['operFlg']) || empty($importData['operFlg'])){
			$error_msg .= '未传入operFlg<br/>';
		}
	
		//operFlg：2，新增；3，修改
		if ($importData['operFlg'] != 2 && $importData['operFlg'] != 3) {
			$error_msg .= '传入operFlg错误<br/>';
		}
	
		if ($importData['operFlg'] == 2 && !isset($importData['creator'])) {
			$error_msg .= '创建人不能为空<br/>';
		}
	
		if ($importData['operFlg'] == 3 && !isset($importData['editor'])) {
			$error_msg .= '修改人不能为空<br/>';
		}
	
		if (empty($importData['mainInfo']['goodsChoiceName'])) {
			$error_msg .= '活动名称不能为空<br/>';
		}
		
		if (empty($importData['mainInfo']['itemID'])) {
			$error_msg .= '套装分类不能为空<br/>';
		}
	
		if (empty($importData['mainInfo']['goodsChoicePrice'])) {
			$error_msg .= '活动价格不能为空<br/>';
		}
		
		if (empty($importData['mainInfo']['goodsCount'])) {
			$error_msg .= '选购数量不能为空<br/>';
		}
		
		if (!is_numeric($importData['mainInfo']['points']) || $importData['mainInfo']['points'] < 0) {
			$error_msg .= '活动积分为大于等于0的整数<br/>';
		}
		
		if (empty($importData['mainInfo']['picName']) && empty($importData['mainInfo']['oldPicName'])) {
			$error_msg .= '展示图片不能为空<br/>';
		}
	
		if (empty($importData['mainInfo']['useStartDate'])) {
			$error_msg .= '开始时间不能为空<br/>';
		}
	
		if (empty($importData['mainInfo']['useEndDate'])) {
			$error_msg .= '结束时间不能为空<br/>';
		}
	
		if ($importData['mainInfo']['useEndDate'] < $importData['mainInfo']['useStartDate']){
			$error_msg .= '开始时间不能大于结束时间<br/>';
		}
		/************************必须有2件以上商品********************************/
		if (count($importData['selectionInfo']) <= 1) {
			$error_msg .= '请添加至少2件商品<br/>';
		}
		/************************必须有2件以上商品********************************/
		if ($importData['operFlg'] == 3 && empty($importData['mainInfo']['goodsChoiceID'])) {
			$error_msg .= '原超值选购传值错误<br/>';
		}
	
		if (!empty($error_msg)){
			$return_data['code'] = 400;
			$return_data['message'] = $error_msg;
			return $return_data;
		}
		/* 传入数据有效性验证end */
	
	
		$operFlg = $importData['operFlg'];//operFlg（2新增，3编辑）
		$creator = $importData['creator'];//创建人
		$editor = $importData['editor'];//修改人
		$goodsChoiceName = trim($importData['mainInfo']['goodsChoiceName']);//活动名称
		$itemID = trim($importData['mainInfo']['itemID']);//套装分类ID
		$goodsChoiceID = trim($importData['mainInfo']['goodsChoiceID']);//活动号
		$goodsChoicePrice = trim($importData['mainInfo']['goodsChoicePrice']);//超值选购价格
		$goodsCount = trim($importData['mainInfo']['goodsCount']);//数量
		$choice_type = trim($importData['mainInfo']['choice_type']);//套装type（1邮购，2网站）
		$points = trim($importData['mainInfo']['points']);//活动积分
		$thumbpic = empty($importData['mainInfo']['picName']) ? trim($importData['mainInfo']['oldPicName']) : '/quanliadmin/docroot/images/promotion/'.trim($importData['mainInfo']['picName']);//活动图片
		$useStartDate = trim($importData['mainInfo']['useStartDate']);//开始时间
		$useEndDate = trim($importData['mainInfo']['useEndDate']);//结束时间
		$selectionInfo = $importData['selectionInfo'];//选购商品（数组）
	
		/*******检测商品是否存在、在售、有库存start********/

		//检测选购商品
		if (!empty($selectionInfo)){
			foreach ($selectionInfo as $goodsList){
				$goods_obj = new entity('goods_sale');
				$goods_obj->product_code = $goodsList["product_code"];
				$goods_obj->useFlg = 1;
				$goods_obj->forsale = 1;
				if (!$this->dbca->fetch($goods_obj)){
					$return_data['code'] = 400;
					$return_data['message'] = '编号['.$goodsList["product_code"].']商品不存在或已下架或没有库存';
					return $return_data;
				}
			}
		}
		/*******检测商品是否存在、在售、有库存end********/
		
		/* 检测套装分类是否存在start */
		$item_obj = new entity('sys_item');
		$item_obj->itemID = $itemID;
		$item_obj->itemCategoryID = 6;
		if (!$this->dbca->fetch($item_obj)){
			$return_data['code'] = 400;
			$return_data['message'] = '所选的分类不存在或已被删除';
			return $return_data;
		}
		/* 检测套装分类是否存在end */
		
		//返回的提示信息
		$message = ($operFlg == 2) ? '新增超值选购成功' : '修改超值选购成功';
	
		//保存到数据库
		try {
	
			//保存到promotion_selection中
			$selection_obj = new entity('promotion_selection');
			$selection_obj->goodsChoiceID = $goodsChoiceID;
			if ($this->dbca->fetch($selection_obj)){
				$selection_obj->editor = $editor;
			}else {
				//如果fetch，且operFlg==3，则弹出错误
				if ($operFlg == 3){
					throw new Exception('您的页面已过期，请刷新页面', -1000);
				}
				$selection_obj->creator = $creator;
				$selection_obj->useFlg = 1;//新增时默认启用
			}
			$selection_obj->goodsChoiceName = $goodsChoiceName;
			$selection_obj->goodsChoicePrice = $goodsChoicePrice;
			$selection_obj->goodsCount = $goodsCount;
			$selection_obj->points = $points;
			$selection_obj->itemID = $itemID;
			$selection_obj->useStartDate = $useStartDate;
			$selection_obj->useEndDate = $useEndDate;
			$selection_obj->thumbpic = $thumbpic;
			$selection_obj->choice_type = $choice_type;
	
			$result_add = $this->dbca->save($selection_obj);
	
	
			if (!empty($result_add) && $operFlg == 2){
				$goodsChoiceID = $this->dbca->insert_id;
			}
	
			if ($operFlg == 3){
				//修改时根据套装号先删除promotion_selection_detail中对应的记录
				$sql_del = 'DELETE FROM promotion_selection_detail WHERE goodsChoiceID = ?';
				$this->dbca->stmt_query($sql_del,'i',$goodsChoiceID);
			}
	
			//将传入的$selectionInfo保存进promotion_selection_detail中
			if (!empty($selectionInfo)){
				foreach ($selectionInfo as $selection_item){
					$detail_obj = new entity('promotion_selection_detail');
					$detail_obj->creator = $creator;
					$detail_obj->goodsChoiceID = $goodsChoiceID;
					$detail_obj->goodsID = trim($selection_item["goodsID"]);
					$detail_obj->postID = trim($selection_item["postID"]);
					$detail_obj->mainPostID = trim($selection_item["mainPostID"]);
					$detail_obj->goodsName = trim($selection_item["goodsName"]);
					$detail_obj->goodsSpec = trim($selection_item["goodsSpec"]);
					$detail_obj->goodsCount = trim($selection_item["goodsCount"]);
					$detail_obj->editor = $editor;
					$detail_obj->goodsType = 3;
					$detail_obj->product_code = trim($selection_item["product_code"]);
					$this->dbca->save($detail_obj,'promotion');
				}
			}
	
			$return_data = array('code'=>200, 'message'=>$message);
			return  $return_data;
		}catch (Exception $e){
			$error_msg = $e->getMessage();
			$return_data = array('code'=>500, 'message'=>$error_msg);
			return  $return_data;
		}
	}
	
	/**
	 * 查询超值选购主题及详情
	 *
	 */
	public function searchPromotionSelection( $arg_array ){
		
		//sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //超值选购活动号
        if (isset($arg_array['goodsChoiceID']) && is_numeric($arg_array['goodsChoiceID'])) {
            $sql .= ' AND goodsChoiceID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['goodsChoiceID'];
        }
        
        //三级商品网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }
        
        //判断活动是否在有效期内
        if (isset($arg_array['startDate']) && is_numeric($arg_array['startDate'])) {
            $sql .= ' AND useStartDate <= ? AND useEndDate >= ? ';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'];
            $params_array[] = $arg_array['startDate'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_selection ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_selection ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
		                    'goodsChoiceID' => $item->goodsChoiceID,
		                    'goodsChoiceName' => $item->goodsChoiceName,
		                    'goodsChoicePrice' => $item->goodsChoicePrice,
		                    'goodsCount' => $item->goodsCount,
		                    'points' => $item->points,
		                    'useFlg' => $item->useFlg,
		                    'useStartDate' => $item->useStartDate,
		                    'useEndDate' => $item->useEndDate,
		                    'editor' => $item->editor,
		                    'thumbpic' => $item->thumbpic,
		                    'choice_type' => $item->choice_type,
		                    'itemID' => $item->itemID
	                	);
            }
            
            foreach ($item_array as &$choice) {
            	
            	$arg_detal_array = array(
            		'goodsChoiceID' => $choice['goodsChoiceID']
            	);
            	
            	$detail_array = $this->searchSelectionDetail($arg_detal_array);
            	
            	$choice['goods'] = $detail_array;
            	
            }
			
            return $item_array;
            
        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
    /**
     * 查询超值选购商品详情信息
     */
    public function searchSelectionDetail( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //超值选购活动号
        if (isset($arg_array['goodsChoiceID']) && is_numeric($arg_array['goodsChoiceID'])) {
            $sql .= ' AND goodsChoiceID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['goodsChoiceID'];
        }
        
        //三级商品网购号
        if (isset($arg_array['postID']) && is_numeric($arg_array['postID'])) {
            $sql .= ' AND psd.postID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['postID'];
        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count 
                					FROM promotion_selection_detail psd
                				JOIN goods_sale gs ON psd.postID = gs.postID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT psd.*,gs.goodsMainPic,gs.salePrice,gs.marketPrice FROM promotion_selection_detail psd JOIN goods_sale gs
            					ON psd.postID = gs.postID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'goodsChoiceID' => $item->goodsChoiceID,
                    'goodsID' => $item->goodsID,
                    'postID' => $item->postID,
                    'mainPostID' => $item->mainPostID,
                    'goodsName' => $item->goodsName,
                    'goodsSpec' => $item->goodsSpec,
                    'goodsCount' => $item->goodsCount,
                    'editor' => $item->editor,
                    'goodsType' => $item->goodsType,
                    'product_code' => $item->product_code,
                    'salePrice' => $item->salePrice,
                    'marketPrice' => $item->marketPrice,
                    'link' => set_goods_link( $item->postID ),
                    'img_link' => set_goods_img_link( $item->goodsMainPic )
                );
            }
			
            return $item_array;
            
        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
	
	
	public function searchSelectionDetailAll ( $importData ){
		//返回数组
		$return_data = array();
			
		//错误信息
		$error = '';
		
		if (isset($importData['page']) && !empty($importData['page']) && !is_numeric($importData['page'])){
			$error .= '当前页码必须为数字<br/>';
		}
		
		if (isset($importData['rp']) && !empty($importData['rp']) && !is_numeric($importData['rp'])){
			$error .= '每页记录数必须为数字<br/>';
		}
		
		if (isset($importData['sortname']) && !empty($importData['sortname']) && !is_string($importData['sortname'])){
			$error .= '排序方式必须为字符串<br/>';
		}
		
		if (isset($importData['sortorder']) && !empty($importData['sortorder']) && !is_string($importData['sortorder'])){
			$error .= '排序方式必须为字符串<br/>';
		}
		
		if (!isset($importData['goodsChoiceID']) || empty($importData['goodsChoiceID'])){
			$error .= '没有传入goodsChoiceID<br/>';
		}
		
		if (!empty($error)){
			$return_data['code'] = 400;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = $error;
			return $return_data;
		}
		
		$goodsChoiceID = trim($importData['goodsChoiceID']);
		$page = isset($importData['page']) ? trim($importData['page']) : '';//当前页
		$rp = isset($importData['rp']) ? trim($importData['rp']) : '';//每页记录数
		$sortname = isset($importData['sortname']) ? trim($importData['sortname']) : '';//排序字段名
		$sortorder = isset($importData['sortorder']) ? trim($importData['sortorder']) : '';//排序方式
		//求总记录数
		$sql_count = 'SELECT COUNT(psd.uuid) countNum FROM promotion_selection_detail psd';
		
		//查询SQL语句
		$sql_search = 'SELECT psd.*, gl.salePrice FROM promotion_selection_detail psd LEFT JOIN goods_list gl ON psd.postID = gl.postID';
		
		//排序
		$str_order = '';
		
		//分页
		$str_limit = '';
		
		//查询条件
		$str_search = ' WHERE';
		
		//查询参数类型
		$type_search = '';
		
		//查询参数数组
		$param_search = array();
		
		//查询条件：权限组ID
		if (!empty($goodsChoiceID)){
			$str_search .= ' AND psd.goodsChoiceID = ?';
			$type_search .= 'i';
			$param_search[] = $goodsChoiceID;
		}
		
		//分页
		if (!empty($page) && !empty($rp)){
			$str_limit = sprintf(' LIMIT %d, %d', ($page - 1) * $rp, $rp);
		}
		
		//排序
		if (!empty($sortname) && !empty($sortorder)){
			$str_order = sprintf(' ORDER BY %s %s', $sortname, $sortorder);
		}
		
		//组装SQL语句
		if (!empty($type_search)){
			$str_search = str_replace('WHERE AND', 'WHERE', $str_search);
			$sql_count = $sql_count.$str_search;
			$sql_search = $sql_search.$str_search.$str_order.$str_limit;
		}else {
			$sql_search = $sql_search.$str_order.$str_limit;
		}
		
		$value_count = empty($type_search) ? $this->dbca->stmt_query($sql_count) : $this->dbca->stmt_query($sql_count,$type_search,$param_search);
		
		if ($value_count){
		
			$return_data['code'] = 200;
		
			//总记录条数
			$return_data['message']['total'] = $value_count[0]->countNum;
		
			//得到查询结果
			$return_data['message']['data'] = empty($type_search) ? $this->dbca->stmt_query($sql_search) : $this->dbca->stmt_query($sql_search,$type_search,$param_search);
		
		}else {
			$return_data['code'] = 200;
			$return_data['message']['total'] = 0;
			$return_data['message']['data'] = '';
		}
		
		return $return_data;
	}
	
	/*
	 * @abstract deleteSelection()      删除超值选购
	 * @param    $choiceIDArr           goodsChoiceID组成的数组
	 * @return   array('code','message')
	 *  */
	public function deleteSelection ( $choiceIDArr ){
		$error = '';
	
		if (empty($choiceIDArr)){
			$error = '请至少选择一条要删除的数据<br/>';
			return array('code' => 400, 'message' => $error);
		}
		
		try {
	
			$this->dbca->beginTransaction();
	
			foreach ($choiceIDArr as $goodsChoiceID){
				
				if (!is_numeric($goodsChoiceID)){
					throw new Exception('goodsChoiceID传值错误', -1000);
				}
				
				//检测promotion_selection中对应数据
				$selection_obj = new entity('promotion_selection');
	
				$selection_obj->goodsChoiceID = $goodsChoiceID;
	
				if (!$this->dbca->fetch($selection_obj)) {
					throw new Exception('活动号：'.$goodsChoiceID.'的超值选购不存在或已被删除', -1000);
				}
				
				//删除promotion_selection表中对应数据
				$this->dbca->delete($selection_obj);
				
				//删除promotion_selection_detail中对应的数据
				$detail_obj = new entity('promotion_selection_detail');
	
				$detail_obj->goodsChoiceID = $goodsChoiceID;
	
				if ($this->dbca->fetch($detail_obj)){
	
					//删除套装商品数据
					$sql_del = 'DELETE FROM promotion_selection_detail WHERE goodsChoiceID = ?';
					$this->dbca->stmt_query($sql_del,'i',$goodsChoiceID);
				}
			}
	
			$this->dbca->commit();
	
			return array( 'code' => 200, 'message' => '删除成功' );
	
		}catch (Exception $e){
			$this->dbca->rollBack();
			$msg = $e->getMessage();
			return array( 'code' => 500, 'message' => $msg );
		}
	}
	
	/**
     * 查询客户优惠券
     * @param array  $arg_array  查询参数数组
     * $arg_array = array(
            'sortname' => string, 排序字段
            'sortorder' => string, 排序方式
            'page' => int, 分页页数
            'rp' => int, 分页页数
     * )
     * @param array  $extend_array
     * $extend_array = array(
            'field' => 1|2|3   1、普通值模糊查询 2、加密值模糊查询 3、in查询
     * )
     * @return array
     */
    public function searchCoupons( &$arg_array, $extend_array = null ) {
    	
		//sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        if (isset($arg_array) && is_array($arg_array)) {

            foreach($arg_array as $key => &$value) {

                if (in_array($key, array('sortname', 'sortorder', 'page', 'rp', 'extend')))
                    continue;

                if(gettype ( $value ) == 'integer'){
                    $bindType = 'i';
                } elseif(gettype ( $value ) == 'double'){
                    $bindType = 'd';
                } elseif (gettype ($value ) == 'string'){
                    $bindType = 's';
                } else{
                    $bindType = 's';
                }

                if (isset($extend_array[$key])) {

                    if ($extend_array[$key] == 1) {

                        $sql .= sprintf(' AND %s LIKE ?', $key);
                        $params_type .= $bindType;
                        $params_array[] = '%' . $value . '%';

                    } else if ($extend_array[$key] == 2) {

                        $sql .= sprintf(' AND %s LIKE ?', $key);
                        $params_type .= $bindType;
                        $params_array[] = '%' . encrypt_paramD($value) . '%';

                    } else if ($extend_array[$key] == 3) {

                        $sql .= sprintf(' AND %s IN (%s)', $key, $value);

                    }

                } else {

                    $sql .= sprintf(' AND %s = ?', $key);
                    $params_type .= $bindType;
                    $params_array[] = $value;
                }
            }

        }

        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {
            $sql .= $arg_array['extend'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }
		
        $coupons_array = array(); //优惠券数组
        
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count 
                					FROM promotion_coupon_code pcc INNER JOIN promotion_coupon pc ON pcc.couponID=pc.couponID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询优惠券信息
            $search_sql = 'SELECT pc.couponID,pcc.createTime,pc.startDate,pc.endDate,pc.couponType,pc.useFlg,pc.couponName,pc.amount,
            				pc.wncode,pc.limitMoney,pc.codeNum,pc.description,pcc.code,pcc.couponID,pcc.billNo 
            					FROM promotion_coupon_code pcc 
			   						INNER JOIN promotion_coupon pc ON pcc.couponID=pc.couponID ' . $sql;
            $coupon_list = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            
            if ($coupon_list) {
            	foreach ($coupon_list as $coupon) {
            		
            		//优惠券状态
            		if ($coupon->billNo) {
            			$coupon->status = '已使用';
            		} else {
            			if (strtotime($coupon->endDate) < time()) {
            				$coupon->status = '已过期';
            			} else {
            				$coupon->status = '未使用';
            			}
            		}
            		
            		$coupons_array[] = array(
            			'couponID' => $coupon->couponID,
            			'createTime' => $coupon->createTime,
            			'startDate' => $coupon->startDate,
            			'endDate' => $coupon->endDate,
            			'couponType' => $coupon->couponType,
            			'useFlg' => $coupon->useFlg,
            			'couponName' => $coupon->couponName,
            			'amount' => $coupon->amount,
            			'wncode' => $coupon->wncode,
            			'limitMoney' => $coupon->limitMoney,
            			'codeNum' => $coupon->codeNum,
            			'code' => $coupon->code,
            			'couponID' => $coupon->couponID,
            			'billNo' => $coupon->billNo,
            			'status' => $coupon->status
            		);
             	}
            }
            
            return $coupons_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	/**
	 * 根据大分类号或中分类号获取中分类或小分类信息
	 *
	 * @param array 参数数组 $arg_array
	 */
	public function getCategory($arg_array){
		if(!$arg_array || !isset($arg_array['flg']) || !isset($arg_array['id']))
			return 1;
			
		if(!in_array($arg_array['flg'], array(1, 2)))
			return 1;
			
		if($arg_array['flg'] == 1 && !is_numeric($arg_array['id']) || intval($arg_array['id']) <= 0)
			return 1;
			
		$cateFlg = trim($arg_array['flg']);
		switch ($cateFlg){
			case 1:	//大分类
				$midData = $this->dbca->stmt_query(sprintf('SELECT midCategoryID,description FROM goods_midcategory WHERE useFlg = 1 AND bigCategoryID = %s', $arg_array['id']));
				if($midData){
					$midInfo = array();
					foreach ($midData as $data){
						$midInfo[$data->midCategoryID] = $data->description;
					}
					
					return $midInfo;
				}else 
					return 1;
			break;	
			case 2:	//中分类
				$idArr = explode('_', $arg_array['id']);
				$smallData = $this->dbca->stmt_query(sprintf('SELECT smallCategoryID,description FROM goods_smallcategory WHERE useFlg = 1 AND bigCategoryID = %s AND midCategoryID = %s', $idArr[0], $idArr[1]));
				if($smallData){
					$smallInfo = array();
					foreach ($smallData as $data){
						$smallInfo[$data->smallCategoryID] = $data->description;
					}
					
					return $smallInfo;
				}else 
					return 1;
			break;
		}
	}
	
	/**
	 * 根据标签组号获得标签信息
	 *
	 * @param array 参数数组 $arg_array
	 */
	public function getTag($arg_array){
		if(!$arg_array || !isset($arg_array['id']))
			return 1;
		else if(!is_numeric($arg_array['id']) || intval($arg_array['id']) <= 0)
			return 1;
			
		//查询标签信息
		$tagInfo = $this->dbca->stmt_query(sprintf('SELECT tagID,tagName FROM goods_tag WHERE tagGroupID = %s AND useFlg = 1', $arg_array['id']));
		if($tagInfo){
			$tagData = array();
			foreach ($tagInfo as $tag){
				$tagData[$tag->tagID] = $tag->tagName;
			}
			
			return $tagData;
		}else 
			return 1;
	}
	
	/**
	 * 根据product_code查询商品信息
	 *
	 * @param array 参数数组 $arg_array
	 */
	public function getGoodsData($arg_array){
		if(!isset($arg_array['product_code']))
			return array('code' => -1, 'message' => '参数错误');

		$product_code = trim($arg_array['product_code']);
		
		$selectorSaleGoods = new entity('goods_sale');
		$selectorSaleGoods->product_code = $product_code;
		if(!$this->dbca->fetch($selectorSaleGoods)) {
			return array('code' => -2, 'message' => sprintf('商家编码「%s」信息不存在', $product_code));
		}
		
		$list_goods = new entity('goods_list');
		$list_goods->postID = $selectorSaleGoods->twoPostID;
		if(!$this->dbca->fetch($list_goods))
			return array('code' => -2, 'message' => sprintf('商家编码「%s」信息不存在', $product_code));
		else{
			if($list_goods->useFlg == 0 || $list_goods->forsale == 0)
				return array('code' => -3, 'message' => sprintf('商品已经下架', $product_code));
		}
		
		return array('code' => 200, 'data' => array('product_code' => $product_code));
	}
	
	/**
	 * 保存商品筛选器信息
	 *
	 * @param 商品筛选器参数数组 $arg_array
	 */
	public function saveSelectorInfo($arg_array){
		if(!is_array($arg_array) || !isset($arg_array['dt']) || !isset($arg_array['rule']) || !isset($arg_array['creator']))
			return array('code' => -1, 'message' => '参数错误');
			
		$selectID     = isset($arg_array['dt']['selectID']) ?  trim($arg_array['dt']['selectID']) : null;			//筛选器ID
		$selectName   = isset($arg_array['dt']['selectName']) ?  trim($arg_array['dt']['selectName']) : null;		//筛选器名称
		$selectorType = isset($arg_array['dt']['selectorType']) ?  trim($arg_array['dt']['selectorType']) : null;	//使用规则
		$description  = isset($arg_array['dt']['description']) ?  trim($arg_array['dt']['description']) : null;		//筛选器描述
		$rule         = $arg_array['rule'];
		
		//检验参数
		$error_msg = '';
		
		if(!empty($selectID)){
			if(!is_numeric($selectID) || intval($selectID) <= 0)
				$error_msg .= '筛选器参数错误<br/>';
		}
		
		if(empty($selectName))
			$error_msg .= '筛选器名称不能为空<br/>';
			
		if(!in_array($selectorType, array(1, 2)))
			$error_msg .= '使用标志错误<br/>';	
			
		if(empty($rule) || !is_array($rule))
			$error_msg .= '请添加筛选规则<br/>';	
			
		if(!empty($error_msg))
			return array('code' => -2, 'message' => $error_msg);
			
		$this->dbca->beginTransaction();	
		try{	
			
			$selector = new entity('goods_selector');
			if(!empty($selectID)){	//编辑
				$selector->selectID = $selectID;
				if(!$this->dbca->fetch($selector))
					throw new Exception(sprintf('筛选器「%d」信息不存在', $selectID), -1000);
					
				$selector->editor = $arg_array['creator'];
			}else{	//添加
				
				//生成筛选器号

                $selectID = $this->promotion_seq_no();
							
				$selector->creator  = $arg_array['creator'];
				$selector->selectID = $selectID;
			}
			$selector->selectName   = $selectName;
			$selector->selectorType = $selectorType;
			$selector->description  = $description;
			
			$this->dbca->save($selector);
			
			//保存规则信息
			if(!empty($selectID))
				$this->dbca->stmt_query(sprintf('DELETE FROM goods_selector_detail WHERE selectID = %d', $selectID));
			
			if($rule){
				foreach ($rule as $val){
					$selector_rule = new entity('goods_selector_detail');
					$selector_rule->creator    = $arg_array['creator'];
					$selector_rule->selectID   = $selectID;
					$selector_rule->selector   = $val[0];
					$selector_rule->selectType = $val[2];
					
					$this->dbca->save($selector_rule, 'promotion');
				}
			}

			$this->dbca->commit();	
			return array('code' => 200, 'message' => '筛选器信息已保存');
		}catch (Exception $e){
			error_log($e->getMessage());
			$this->dbca->rollBack();	
			if($e->getCode() == -1000)
				return array('code' => -3, 'message' => $e->getMessage());
			else 
				return array('code' => -4, 'message' => '保存数据失败');	
		}
	}
	
	/**
	 * 查询用户筛选器列表
	 * @param $arg_array 参数数组
	 * @author sunchun
	 *
	 */
	public function userSelectorList(&$arg_array){
		//sql字符串
        $sql = '';
        
        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
        
         //选择器ID
        if (isset($arg_array['selectID']) && is_numeric($arg_array['selectID']) && intval($arg_array['selectID']) > 0) {
            $sql .= ' AND selectID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['selectID'];
        }

        //选择器名称
        if (isset($arg_array['selectDisplayName']) && trim($arg_array['selectDisplayName']) != '') {
            $sql .= ' AND selectDisplayName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['selectDisplayName']) . '%';
        }
        
        if(!empty($sql))
        	$sql = 'WHERE ' . substr($sql, 4);

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计促销行数
                $search_sql = 'SELECT COUNT(*) AS count FROM cust_selector ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询商品促销信息
            $search_sql = 'SELECT * FROM cust_selector ' . $sql;;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
                
            return $temp_item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
	}
	
	/**
	 * 删除用户筛选器或筛选规则
	 *
	 * @param array 参数数组 $arg_array
	 */
	public function deleteUserSelector($arg_array){
		$delete_str = isset($arg_array['delete_str']) ? trim($arg_array['delete_str']) : null;
		if(empty($delete_str))
			return array('code' => 400, 'message' => '参数错误');
			
		$deleteArray = explode('|', $delete_str);
		if($deleteArray){
			try{
				foreach ($deleteArray as $val){
					//截成数组判断是删除筛选器还是筛选规则
					$valArray = explode('_', $val);
					if(count($valArray) == 2){
						//筛选规则
						$this->dbca->stmt_query(sprintf('DELETE FROM cust_selector_detail WHERE selectID = %s AND selectType = %s', $valArray[0], $valArray[1]));
					}else{
						//筛选器
						$this->dbca->stmt_query(sprintf('DELETE FROM cust_selector WHERE selectID = %s', $valArray[0]));
						
						//删除筛选器对应的规则
						$this->dbca->stmt_query(sprintf('DELETE FROM cust_selector_detail WHERE selectID = %s', $valArray[0]));
					}
				}
			}catch (Exception $e){
				error_log($e->getMessage());
				return array('code' => 500, 'message' => '保存数据库失败');
			}
		}
		return array('code' => 200, 'message' => '筛选器信息已删除');
	}
	
	/**
	 * 用户筛选器查询用户信息
	 *
	 * @param array 参数数组 $arg_array
	 */
	public function getUserInfo($arg_array){
		if(!$arg_array || !isset($arg_array['userName']))
			return array('code' => 400, 'message' => '请输入用户名');
			
		$userName = trim($arg_array['userName']);
		$userData = $this->dbca->stmt_query(sprintf('SELECT pcustID,custID FROM cust_master WHERE custID LIKE %s', '"%' . $userName . '%"'));
		
		$userArr = array();
		if($userData){
			foreach ($userData as $user){
				$userArr[$user->pcustID] = $user->custID;
			}
		}
		return array('code' => 200, 'message' => $userArr);
	}
	
	/**
	 * 保存用户筛选器信息
	 *
	 * @param 用户筛选器参数数组 $arg_array
	 */
	public function saveUserSelectorInfo($arg_array){
		if(!is_array($arg_array) || !isset($arg_array['dt']) || !isset($arg_array['rule']) || !isset($arg_array['creator']))
			return array('code' => -1, 'message' => '参数错误');
			
		$selectID      = isset($arg_array['dt']['selectID']) ?  trim($arg_array['dt']['selectID']) : null;			//筛选器ID
		$selectName    = isset($arg_array['dt']['selectName']) ?  trim($arg_array['dt']['selectName']) : null;		//筛选器名称
		$description   = isset($arg_array['dt']['description']) ?  trim($arg_array['dt']['description']) : null;	//筛选器描述
		$rule	       = $arg_array['rule'];																		//筛选
		
		//检验参数
		$error_msg = '';
		
		if(!empty($selectID)){
			if(!is_numeric($selectID) || intval($selectID) <= 0)
				$error_msg .= '筛选器参数错误<br/>';
		}
		
		if(empty($selectName))
			$error_msg .= '筛选器名称不能为空<br/>';
			
		if(empty($rule) || !is_array($rule))
			$error_msg .= '请添加筛选规则<br/>';	
			
		if(!empty($error_msg))
			return array('code' => -2, 'message' => $error_msg);
			
		$this->dbca->beginTransaction();	
		try{	
			
			$selector = new entity('cust_selector');
			if(!empty($selectID)){	//编辑
				$selector->selectID = $selectID;
				if(!$this->dbca->fetch($selector))
					throw new Exception(sprintf('筛选器「%d」信息不存在', $selectID), -1000);

			}else	//添加		
				$selector->creator  = $arg_array['creator'];
			
			$selector->selectDisplayName   = $selectName;
			$selector->description  	   = $description;
			$selector->useFlg  	           = 1;
			
			$this->dbca->save($selector, 'promotion');
			
			//保存规则信息
			if(!empty($selectID))
				$this->dbca->stmt_query(sprintf('DELETE FROM cust_selector_detail WHERE selectID = %d', $selectID));
			else{
				//获取selectID
				$selectMax = $this->dbca->stmt_query('SELECT MAX(selectID) maxID FROM cust_selector');
				$selectID = $selectMax[0]->maxID;
			}
			
			if($rule){
				foreach ($rule as $val){
					//保存用户筛选详情
					$selector_rule = new entity('cust_selector_detail');
					$selector_rule->creator    = $arg_array['creator'];
					$selector_rule->selectID   = $selectID;
					$selector_rule->selectType = $val[0];
					$selector_rule->selector   = $val[1];
					$selector_rule->ruleFLg    = $val[2];
		
					$this->dbca->save($selector_rule, 'promotion');
				}
			}

			$this->dbca->commit();	
			return array('code' => 200, 'message' => '筛选器信息已保存');
		}catch (Exception $e){
			error_log($e->getMessage());
			$this->dbca->rollBack();	
			if($e->getCode() == -1000)
				return array('code' => -3, 'message' => $e->getMessage());
			else 
				return array('code' => -4, 'message' => '保存数据失败');	
		}
	}

    /**
     * 新增或修改闪购活动
     * @param array $arg_array 闪购活动参数
     * @return array
     * @throws Exception
     */
    public function saveSecondKill( $arg_array ) {

        if (!isset($arg_array['kill_id'], $arg_array['product_code'], $arg_array['kill_price'], $arg_array['max_sale_amount'], $arg_array['startDate'],
            $arg_array['endDate'], $arg_array['startTime'], $arg_array['useFlg'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //公共类
        $commHandler = new commHandler($this->dbca);

        if (empty($arg_array['product_code'])) {
            return array( 'code' => 400, 'message' => '闪购商品编号不能为空' );
        }

        if (!$commHandler->isMoney($arg_array['kill_price'])) {
            return array( 'code' => 400, 'message' => '闪购价必须大于等于0的数字' );
        }

        if (!$commHandler->isInteger($arg_array['max_sale_amount'], 1)) {
            return array( 'code' => 400, 'message' => '闪购总数量必须是大于0的整数' );
        }

        if (!$commHandler->isDate($arg_array['startDate']) || !$commHandler->isDate($arg_array['endDate'])) {
            return array( 'code' => 400, 'message' => '闪购开始结算日期不能为空' );
        } else if ($arg_array['startDate'] > $arg_array['endDate']) {
            return array( 'code' => 400, 'message' => '开始日期不能大于结束日期' );
        }

        if (!$commHandler->isInteger($arg_array['startTime'], 1) && $arg_array['startTime'] <= 23) {
            return array( 'code' => 400, 'message' => '请选择闪购开始时间' );
        }

        if (!in_array($arg_array['useFlg'], array(0, 1))) {
            return array( 'code' => 400, 'message' => '使用标志错误' );
        }

        //实例化商品类
        $goodsHandler = new goodsHandler( $this->dbca );

        try{

            //查询商品信息
            $goods_arg_array = array(
                'product_code' => $arg_array['product_code'],
                'useFlg' => 1,
                'forsale' => 1
            );
            $goods_array = $goodsHandler->searchGoodsSale( $goods_arg_array );
            if (!$goods_array)
                throw new Exception('商品信息没有找到', 404);

            $s_obj = new entity('promotion_secondkill');
            if ($arg_array['kill_id'] > 0) {
                $s_obj->kill_id = $arg_array['kill_id'];
                if (!$this->dbca->fetch($s_obj)) {
                    throw new Exception('闪购活动信息没有找到', 404);
                }
            } else {
                $s_obj->kill_id = $commHandler->generate_seqno('seqno_secondkill');
                $s_obj->creator = $arg_array['creator'];
            }
            $s_obj->startDate = $arg_array['startDate'];
            $s_obj->endDate = $arg_array['endDate'];
            $s_obj->startTime = $arg_array['startTime'];
            $s_obj->postID = $goods_array['postID'];
            //$s_obj->product_code = $goods_array['product_code'];
            $s_obj->goodsName = $goods_array['goodsName'];
            $s_obj->goodsLink = $goods_array['link'];
            $s_obj->picLink = $goods_array['img_link'];
            //$s_obj->salePrice = $goods_array['salePrice'];
            $s_obj->kill_price = $arg_array['kill_price'];
            $s_obj->max_sale_amount = $arg_array['max_sale_amount'];
            $s_obj->useFlg = $arg_array['useFlg'];
            $this->dbca->save($s_obj);

            return array( 'code' => 200 , 'message' => '闪购活动保存成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500 , 'message' => '系统错误' );
            }

        }


    }


    /**
     * 查询商品闪购信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *   'product_code' => string 商品编号
     *   'goodsName' => string 商品名称
     *   'seckillDate' => string 日期
     *   'kill_id' => int 闪购ID
     *   'useFlg' => int 使用标志
     *   'sortname' => string 排序字段
     *   'sortorder' => string 排序方式
     *   'page' => int 分页页码
     *   'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchSeconKillList( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //商品编号
        if (isset($arg_array['product_code']) && !empty($arg_array['product_code']) ) {
            $sql .= ' AND product_code LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['product_code']) . '%';
        }

        //商品名称
        if (isset($arg_array['goodsName']) && !empty($arg_array['goodsName']) ) {
            $sql .= ' AND goodsName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.trim($arg_array['goodsName']).'%';
        }

        //秒杀日期
        if (isset($arg_array['seckillDate']) && !empty($arg_array['seckillDate']) ) {
            $sql .= ' AND startDate >= ? AND startDate <= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['seckillDate'] . ' 00:00:00';
            $params_array[] = $arg_array['seckillDate'] . ' 23:59:59';
        }

        //秒杀号
        if (isset($arg_array['kill_id']) && !empty($arg_array['kill_id']) ) {
            $sql .= ' AND kill_id = ?';
            $params_type .= "i";
            $params_array[] = trim($arg_array['kill_id']);
        }

        //启用标志
        if (isset($arg_array['useFlg']) && is_numeric($arg_array['useFlg']) ) {
            $sql .= ' AND useFlg = ?';
            $params_type .= "i";
            $params_array[] = trim($arg_array['useFlg']);
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_secondkill ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_secondkill ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach ($temp_item_array as &$item){
                $getCodePrice = $this->dbca->stmt_query('select * from promotion_secondkill ps inner join goods_sale gs on ps.postID = gs.postID where ps.postID=?','i',$item->postID);
                $item_array[] = array(
                    'kill_id' => $item->kill_id,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'startTime' => $item->startTime,
                    'postID' => $item->postID,
                    'goodsName' => $item->goodsName,
                    'goodsLink' => $item->goodsLink,
                    'picLink' => $item->picLink,
                    'kill_price' => $item->kill_price,
                    'max_sale_amount' => $item->max_sale_amount,
                    'saled_amount' => $item->saled_amount,
                    'praise' => $item->praise,
                    'useFlg' => $item->useFlg,
                    'product_code' => $getCodePrice[0]->product_code,
                    'salePrice' => $getCodePrice[0]->salePrice
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 修改闪购活动使用状态
     * @param int $kill_id 活动ID
     * @return array
     * @throws Exception
     */
    public function changeSecondKillUse( $kill_id ) {

        if (!isset($kill_id) || !is_numeric($kill_id)) {
            return array( 'code' => 400 , 'message' => '参数错误' );
        }

        try{

            $s_obj = new entity('promotion_secondkill');
            $s_obj->kill_id = $kill_id;
            if (!$this->dbca->fetch($s_obj)) {
                throw new Exception('闪购活动信息没有找到', 404);
            }
            $useFlg = $s_obj->useFlg;
            if ($s_obj->useFlg == 0) {
                $s_obj->useFlg = 1;
            } else {
                $s_obj->useFlg = 0;
            }
            $this->dbca->save($s_obj);

            return array( 'code' => 200 , 'message' => $useFlg ? '闪购禁用成功' : '闪购启用成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode() , 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500 , 'message' => '系统错误' );
            }

        }

    }

    /**
     * 删除闪购活动
     * @param array $arg_array 闪购活动ID数组
     * @return array
     */
    public function deleteSecondKill ($arg_array) {

        if (!isset($arg_array) || !is_array($arg_array) || empty($arg_array)) {
            return array( 'code' => 400 , 'message' => '参数错误' );
        }

        try {

            foreach ($arg_array as &$kill_id){
                $this->dbca->stmt_query('DELETE FROM promotion_secondkill WHERE kill_id = ?', 'i', $kill_id);
            }

            return array('code' => 200 , 'message' => '删除活动删除成功');

        } catch (Exception $e) {
            error_log($e->getMessage());
            return array('code' => 500 , 'message' => '系统错误');
        }

    }

    /**
     * 秒杀商品添加赞
     * @param  $kill_id   int 秒杀号
     * @param $pcustID int 客户号
     */
    public function secondeKillPraise($kill_id,$pcustID){

        if(!isset($kill_id) || !is_numeric($kill_id) ){
            return array('code' => 400 ,'message' => "参数错误");
        }

        //检查当前用户是否已赞过
        $promotion_secondkill_praise = new entity('promotion_secondkill_praise');
        $promotion_secondkill_praise->kill_id = $kill_id;
        $promotion_secondkill_praise->pcustID = $pcustID;
        if($this->dbca->fetch($promotion_secondkill_praise)){
            return array('code' => 406 ,'message' => "您已'赞'过此商品,请勿重复");
        }

        //赞的数量+1
        $promotion_secondkill = new entity('promotion_secondkill');
        $promotion_secondkill->kill_id = $kill_id;
        if(!$this->dbca->fetch($promotion_secondkill)){
            return array('code' => 404 ,'message' => "未找到秒杀的商品信息");
        }
        $promotion_secondkill->praise++;

        try{

            $this->dbca->beginTransaction();

            $this->dbca->save($promotion_secondkill_praise);

            $this->dbca->save($promotion_secondkill);

            $this->dbca->commit();

            return array('code' => 200 , 'message' => 'ok' ,'praise' => $promotion_secondkill->praise,'kill_id' => $kill_id);

        }catch (Exception $e){
            $this->dbca->rollBack();
            error_log($e->getMessage());
            return array('code' => 500 , 'message' => '系统错误');
        }

    }

    /**
     * 会员促销发放
     * @param int $pcustID 会员号
     * @param string $custID 会员名
     * @param int $source 1、注册 2、登录 3、签到
     * @param object $eai EAI类实例
     * @return bool
     */
    public function grantCustPromotion( $pcustID, $custID, $source, $eai ) {

        //查询会员促销参数
        $arg_array = array(
            'startDate' => date(G_DEFAULT_DATETIME_FORMAT),
            'source' => $source,
            'useFlg' => 1,
            'sortname' => 'promotionID',
            'sortorder' => 'DESC'
        );

        //查询会员促销信息
        $promotion_array = $this->searchPromotionCustomerInfo( $arg_array );
        if (!$promotion_array) {
            return array( 'code' => 400, 'message' => '没有促销活动' );
        }

        $data = array(
            'points' => 0,
            'coupon' => array()
        );

        foreach($promotion_array as &$p) {

            //检查活动领取记录（登录、签到、完善资料）
            if ($source == 2 || $source == 3 || $source == 6) {

                $log_obj = new entity('promotion_customer_log');
                $log_obj->promotionID = $p['promotionID'];
                $log_obj->pcustID = $pcustID;
                $log_obj->date = date(G_DEFAULT_DATE_FORMAT);
                if ($this->dbca->fetch($log_obj)) {
                    continue;
                }

            }

            if ($p['type'] == 1) { //送积分

                if (!is_numeric($p['points']) || $p['points'] <= 0) {
                    continue;
                }

                //调用CRM会员账户修改接口
                $arg_array = array(
                    'pcustID' => $pcustID,
                    'payTypeID' => G_PAYTYPE_POINTS,
                    'amount' => $p['points'],
                    'operator' => '系统',
                    'remark' => $p['title'] . '，积分+' . $p['points'],
                    'externalTranCode' => '',
                    'source' => ''
                );
                $eai->memberRecharge( $arg_array, $this->dbca );

                $data['points'] += $p['points'];

            } else if ($p['type'] == 2)             { //送优惠券

                //查询需要发放的优惠券
                $arg_array = array(
                    'promotionID' => $p['promotionID']
                );
                $coupon_array = $this->searchCustPromotionCoupon( $arg_array );
                if (!$coupon_array) {
                    continue;
                }

                //加载优惠券类
                quanli_include('module/base/couponHandler.class.php');

                //实例化优惠券类
                $couponHandler = new couponHandler( $this->dbca );

                //发货优惠券
                foreach($coupon_array as &$c) {

                    $c_array = array();
                    for($i = 0; $i < $c['couponNum']; $i++) {
                        $c_array[] = $custID;
                    }
                    $couponHandler->createCouponCode($c['couponID'], $c_array);

                    $data['coupon'][] = sprintf('%d张%s优惠券', $c['couponNum'], $c['couponName']);

                }

            }

            //保存促销活动领取记录
            if ($source == 2 || $source == 3|| $source == 6) {

                $this->dbca->save($log_obj);

            }

        }

        return array( 'code' => 200, 'message' => 'ok', 'data' => $data );

    }


    /**
     * 查询会员促销信息
     * $arg_array = array (
     *   'promotionID' => int 促销ID
     *   'title' => string  活动名称
     *   'source' => int 活动类型  1、注册 2、登录 3、签到
     *   'type' => int 促销类型    1、送积分 2、送优惠券
     *   'startDate' => string 促销日期
     *   'sortname' => string 排序字段
     *   'sortorder' => string 排序方式
     *   'page' => int 分页页码
     *   'rp' => int 分页页数
     * )
     */
    public function searchPromotionCustomerInfo( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();


        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //活动标题
        if (isset($arg_array['title']) &&  !empty($arg_array['title']) ) {
            $sql .= ' AND title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.trim($arg_array['title']).'%';
        }

        //活动类型
        if (isset($arg_array['source']) && is_numeric($arg_array['source'])) {
            $sql .= ' AND source = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['source'];
        }

        //促销类型
        if (isset($arg_array['type']) && is_numeric($arg_array['type'])) {
            $sql .= ' AND type = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['type'];
        }

        //促销日期
        if (isset($arg_array['startDate']) && trim($arg_array['startDate']) != '') {
            $sql .= ' AND startDate <= ? AND endDate >= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] ;
            $params_array[] = $arg_array['startDate'] ;
        }

        //使用标志
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_customer ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_customer ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'createTime' => $item->createTime,
                    'promotionID' => $item->promotionID,
                    'title' => $item->title,
                    'source' => $item->source,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'type' => $item->type,
                    'points' => $item->points,
                    'useFlg' => $item->useFlg
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**
     * 保存会员促销
     *
     * @param unknown_type $arg_array
     */
    public function savePromotionCustomerInfo( $arg_array ){
        //参数检查
        if(!isset($arg_array['promotionID'] ,$arg_array['title'],$arg_array['source'],$arg_array['startDate'] ,$arg_array['endDate'],$arg_array['type'] , $arg_array['creator']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        $type  	   	 = $arg_array['type'] ;
        $source 	 = $arg_array['source'] ;
        $title 	   	 = htmlspecialchars(trim($arg_array['title'])) ;
        $startDate 	 = $arg_array['startDate'] ;
        $endDate   	 = $arg_array['endDate'] ;
        $useFlg  	 = $arg_array['useFlg'] ;
        $promotionID = $arg_array['promotionID'] ;

        //规则参数查检
        $error_msg = '' ;

        if($title == '')
            $error_msg .= '促销活动标题不能为空</br>' ;

        if(!in_array($source , array(1,2,3,4,5,6)))
            $error_msg .= '活动类型参数错误</br>';

        if(!in_array($type , array(1,2)))
            $error_msg .= '促销类型参数错误</br>';

        if($startDate == '' || $endDate == '')
            $error_msg .= '促销开始和结束时间不能为空</br>' ;

        if($startDate > $endDate)
            $error_msg .= '促销开始时间不能大于结束时间</br>' ;

        if(!in_array($useFlg , array(0,1)))
            $error_msg .= '使用状态参数错误</br>';

        if( $error_msg != '' )
            return array( 'code' => 400, 'message' => $error_msg );

        $points = '';         //记录积分
        $couponArray = '';  //记录优惠券信息

        if($type == 1){
            if(!isset($arg_array['points']))
                return array( 'code' => 400, 'message' => '赠送积分不能为空' );

            $points = $arg_array['points'];

        }elseif( $type == 2 ){
            if(!isset( $arg_array['couponLine'] ))
                return array( 'code' => 400, 'message' => '缺少参数' );

            $couponArray  = $arg_array['couponLine'];//优惠券明细

        }

        $this->dbca->beginTransaction() ;
        try{

            if($promotionID != ""){

                //检查优惠券明细
                $promotion_coupon = array();
                if($couponArray){
                    foreach ($couponArray as $couponVal){

                        //检查优惠券数量是否正确
                        if(!is_numeric($couponVal[0]) || intval($couponVal[0]) <=0)
                            throw new Exception('优惠券的张数必须为正整数', 400) ;

                        if(!is_numeric($couponVal[1]) || intval($couponVal[1]) <=0)
                            throw new Exception('优惠券的编号必须为正整数', 400) ;

                        $accountCoupon = new entity('promotion_coupon');
                        $accountCoupon->couponID = $couponVal[1];
                        if(!$this->dbca->fetch($accountCoupon))
                            throw new Exception(sprintf('优惠券「%s」信息不存在' , $couponVal[1]), 400) ;

                        $coupon_detail = new entity('promotion_customer_coupon');
                        $coupon_detail->creator     = $arg_array['creator'];
                        $coupon_detail->promotionID = $promotionID;
                        $coupon_detail->couponID    = $couponVal[1];
                        $coupon_detail->couponNum   = $couponVal[0];
                        $coupon_detail->couponName  = $accountCoupon->couponName ;

                        $promotion_coupon[] = $coupon_detail;
                    }
                }

                //保存促销信息
                $save_promotion_customer = new entity('promotion_customer') ;
                $save_promotion_customer->promotionID 	 = $promotionID ;
                if(!$this->dbca->fetch($save_promotion_customer))
                    throw new Exception(sprintf('促销活动号「%s」的促销不存在' ,$promotionID), 400) ;

                $save_promotion_customer->title   	  	 = $arg_array['title'] ;
                $save_promotion_customer->startDate  	 = $arg_array['startDate'] ;
                $save_promotion_customer->endDate	  	 = $arg_array['endDate'] ;
                $save_promotion_customer->source		 = $arg_array['source'] ;
                $save_promotion_customer->type		  	 = $type ;
                $save_promotion_customer->useFlg		 = $useFlg;

                if( $points )
                    $save_promotion_customer->points     = $points ;

                $this->dbca->save($save_promotion_customer);

                //删除老的优惠券详情
                $this->dbca->stmt_query('DELETE FROM promotion_customer_coupon WHERE promotionID=?' , 'i' , $promotionID);

                //保存优惠券明细
                if($promotion_coupon) {
                    foreach ($promotion_coupon as &$c_l) {
                        $this->dbca->save($c_l) ;
                    }
                }

                $this->dbca->commit() ;
                return array( 'code' => 200, 'message' => '会员促销更新成功' );
            }else{

                //生成促销活动号
                $promotionID = $this->promotion_seq_no() ;

                //检查优惠券明细
                $promotion_coupon = array();
                if($couponArray){
                    foreach ($couponArray as $couponVal){

                        //检查优惠券数量是否正确
                        if(!is_numeric($couponVal[0]) || intval($couponVal[0]) <=0)
                            throw new Exception('优惠券的张数必须为正整数', 400) ;

                        if(!is_numeric($couponVal[1]) || intval($couponVal[1]) <=0)
                            throw new Exception('优惠券的编号必须为正整数', 400) ;

                        $accountCoupon = new entity('promotion_coupon');
                        $accountCoupon->couponID = $couponVal[1];
                        if(!$this->dbca->fetch($accountCoupon))
                            throw new Exception(sprintf('优惠券「%s」信息不存在' , $couponVal[1]), 400) ;

                        $coupon_detail = new entity('promotion_customer_coupon');
                        $coupon_detail->creator     = $arg_array['creator'];
                        $coupon_detail->promotionID = $promotionID;
                        $coupon_detail->couponID    = $couponVal[1];
                        $coupon_detail->couponNum   = $couponVal[0];
                        $coupon_detail->couponName  = $accountCoupon->couponName ;

                        $promotion_coupon[] = $coupon_detail;
                    }
                }

                //保存促销信息
                $save_promotion_customer = new entity('promotion_customer') ;
                $save_promotion_customer->creator    	 = $arg_array['creator'] ;
                $save_promotion_customer->title   	  	 = $arg_array['title'] ;
                $save_promotion_customer->startDate  	 = $arg_array['startDate'] ;
                $save_promotion_customer->endDate	  	 = $arg_array['endDate'] ;
                $save_promotion_customer->source		 = $arg_array['source'] ;
                $save_promotion_customer->type		  	 = $type ;
                $save_promotion_customer->promotionID 	 = $promotionID ;
                $save_promotion_customer->useFlg		 = $useFlg;

                if( $points )
                    $save_promotion_customer->points     = $points ;

                $this->dbca->save($save_promotion_customer);

                //保存优惠券明细
                if($promotion_coupon) {
                    foreach ($promotion_coupon as &$c_l) {
                        $this->dbca->save($c_l) ;
                    }
                }

                $this->dbca->commit() ;
                return array( 'code' => 200, 'message' => '会员促销保存成功' );
            }

        }catch (Exception $e) {

            $this->dbca->rollBack() ;
            if ($e->getCode() > 0)
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询会员促销的优惠券详情
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null
     */
    public function searchCustPromotionCoupon( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_customer_coupon ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_customer_coupon ' . $sql;;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array) {
                return null;
            }

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'promotionID' => $item->promotionID,
                    'couponID' => $item->couponID,
                    'couponName' => $item->couponName,
                    'couponNum' => $item->couponNum
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 查询积分兑换信息
     * $arg_array = array (
     *   'promotionID' => int 促销ID
     *   'promotionName' => string  促销活动名称
     *   'couponID' => int 优惠券ID
     *   'useFlg' => int   使用状态标志
     *   'startDate' => string 促销日期
     *   'sortname' => string 排序字段
     *  'sortorder' => string 排序方式
     *   'page' => int 分页页码
     *   'rp' => int 分页页数
     * )
     */
    public function searchPointsConvertInfo( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //促销活动名称
        if (isset($arg_array['promotionName']) &&  !empty($arg_array['promotionName']) ) {
            $sql .= ' AND promotionName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.trim($arg_array['promotionName']).'%';
        }

        //使用状态标志
        if ( isset($arg_array['useFlg']) && in_array($arg_array['useFlg'] , array(0,1)) ) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //优惠券ID
        if (isset($arg_array['couponID']) && is_numeric($arg_array['couponID'])) {
            $sql .= ' AND couponID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['couponID'];
        }

        //促销日期
        if (isset($arg_array['startDate']) && trim($arg_array['startDate']) != '') {
            $sql .= ' AND startDate <=? AND endDate >=?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] ;
            $params_array[] = $arg_array['startDate'] ;
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_points_coupon ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_points_coupon ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'creator'  => $item->creator,
                    'createTime' => $item->createTime,
                    'promotionID' => $item->promotionID,
                    'promotionName' => $item->promotionName,
                    'points' => $item->points,
                    'couponID' => $item->couponID,
                    'couponName' => $item->couponName,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'useFlg' => $item->useFlg
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }
    
    /**
     * 查询积分商城促销
     * $arg_array = array (
     *   'promotionID' => int 促销ID
     *   'promotionName' => string  促销活动名称
     *   'couponID' => int 优惠券ID
     *   'useFlg' => int   使用状态标志
     *   'startDate' => string 促销日期
     *   'sortname' => string 排序字段
     *  'sortorder' => string 排序方式
     *   'page' => int 分页页码
     *   'rp' => int 分页页数
     * )
     */
    public function searchPointsMall( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //促销活动名称
        if (isset($arg_array['promotionName']) &&  !empty($arg_array['promotionName']) ) {
            $sql .= ' AND title LIKE ?';
            $params_type .= 's';
            $params_array[] = '%'.trim($arg_array['title']).'%';
        }

        //使用状态标志
        if ( isset($arg_array['useFlg']) && in_array($arg_array['useFlg'] , array(0,1)) ) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //促销日期
        if (isset($arg_array['startDate']) && trim($arg_array['startDate']) != '') {
            $sql .= ' AND startDate <=? AND endDate >=?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] ;
            $params_array[] = $arg_array['startDate'] ;
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
		
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_pointsmall ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_pointsmall ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'promotionID'  => $item->promotionID,
                    'promotionName' => $item->promotionName,
                    'promotionIndex' => $item->promotionIndex,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate,
                    'type' => $item->type,
                    'remark' => $item->remark,
                    'useFlg' => $item->useFlg
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }
    
    /**
     * 查询积分商城积分促销详情
     * $arg_array = array (
     *   'promotionID' => int 促销ID
     *   'promotionName' => string  促销活动名称
     *   'couponID' => int 优惠券ID
     *   'useFlg' => int   使用状态标志
     *   'startDate' => string 促销日期
     *   'sortname' => string 排序字段
     *  'sortorder' => string 排序方式
     *   'page' => int 分页页码
     *   'rp' => int 分页页数
     * )
     */
    public function searchPointsMallDetail( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }
        
        //商家编码/优惠券ID
        if (isset($arg_array['id']) && is_numeric($arg_array['id'])) {
            $sql .= ' AND id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['id'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
		
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_pointsmall_detail ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_pointsmall_detail ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'promotionID'  => $item->promotionID,
                    'id'  => $item->id,
                    'name' => $item->name,
                    'points'  => $item->points,
                    'pointsPrice'  => $item->pointsPrice
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }

    /**保存积分商城促销
     * @param $arg_array  参数数组
     * @return array
     * @throws Exception
     */
    public function savePointsMall( &$arg_array ){
    	
    	if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID']) && !is_numeric($arg_array['promotionID'])) {
    		return array( 'code' => 400, 'message' => '参数错误' );
    	}
    	
    	//活动名称
    	if (!isset($arg_array['promotionName']) || empty($arg_array['promotionName'])) {
    		return array( 'code' => 400, 'message' => '请输入活动名称' );
    	}
    	
    	//活动别名
    	if (!isset($arg_array['promotionIndex']) || empty($arg_array['promotionIndex'])) {
    		return array( 'code' => 400, 'message' => '请输入活动别名' );
    	}
    	
    	//促销时间
    	if (!isset($arg_array['startDate'],$arg_array['endDate']) || empty($arg_array['startDate']) || empty($arg_array['endDate'])) {
    		return array( 'code' => 400, 'message' => '请选择促销活动时间' );
    	}
    	
    	if ($arg_array['startDate'] > $arg_array['endDate']) {
    		return array( 'code' => 400, 'message' => '开始时间不能大于结束时间' );
    	}
		    	
    	//使用状态
    	if (!isset($arg_array['useFlg']) || ($arg_array['useFlg'] != '0' && $arg_array['useFlg'] != '1')) {
    		return array( 'code' => 400, 'message' => '请选择使用状态' );
    	}
    	
    	//类型 1.积分兑换优惠券 2.积分兑换商品 3.积分换购商品
    	if (!isset($arg_array['type']) || !in_array($arg_array['type'],array(1,2,3))) {
    		return array( 'code' => 400, 'message' => '请选择积分活动类型' );
    	}
    	
    	if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
    		$flg = 3; //编辑
    	} else {
    		$flg = 2; //添加
    	}
    	
    	if ($arg_array['type'] == 1) { //积分换券
    		
    		$select_array = array();
    		//获取积分兑换优惠券信息
    		foreach ($arg_array as $key=>$value) {
    			
    			if (substr($key,0,11) == 'row_points_') {
    				
    				$temp_arr = explode('_',$value);
    				
	    			if (count($temp_arr) != 2) {
	    				return array( 'code' => 400, 'message' => '参数错误' );
	    			}
	    			
	    			//$select_array[优惠券ID] = 积分;
	    			$select_array[$temp_arr[1]] = array(
	    						'points' => $temp_arr[0],
	    						'couponName' => $arg_array['row_couponName_'.$temp_arr[1]]
	    				);
    			}
    			
    		}
    		
    		if (empty($select_array)) {
    			return array( 'code' => 400, 'message' => '请添加积分兑换优惠券' );
    		}
    		
    		try {
    			
    			//开启事务
	            $this->dbca->beginTransaction();
    			
	            $pointsmall = new entity('promotion_pointsmall');
	            
	            if ($flg == 3) {  //编辑
	            	
	            	$promotionID = $arg_array['promotionID'];
	            	
	            	//查询促销是否存在
	            	$pointsmall->promotionID = $promotionID;
	            	if (!$this->dbca->fetch($pointsmall)) {
	            		throw new Exception('该促销不存在', -1000);
	            	}
	            	$pointsmall->editor = $arg_array['creator'];
	            	
	            } else { //添加
	            	
	            	//获取促销ID
	            	$promotionID = $this->promotion_seq_no();
	            	
	            	$pointsmall->creator = $arg_array['creator'];
	            	$pointsmall->editor = $arg_array['creator'];
	            	$pointsmall->promotionID = $promotionID;
	            }
	            
	            $pointsmall->promotionName = $arg_array['promotionName'];
	            $pointsmall->promotionIndex = $arg_array['promotionIndex'];
	            $pointsmall->startDate = $arg_array['startDate'];
	            $pointsmall->endDate = $arg_array['endDate'];
	            $pointsmall->type = $arg_array['type'];
	            $pointsmall->remark = $arg_array['remark'];
	            $pointsmall->useFlg = $arg_array['useFlg'];
	            $this->dbca->save($pointsmall);
	            
	            //删除已有的促销详情
            	$sql = 'DELETE FROM promotion_pointsmall_detail WHERE promotionID = ' . $promotionID;
            	$this->dbca->execute($sql);
	            
	            foreach ($select_array as $k=>$v) {
	            	$pointsmall_detail = new entity('promotion_pointsmall_detail');
	            	
	            	if ($flg == 3) {
	            		$pointsmall_detail->editor = $arg_array['creator'];
	            	} else {
	            		$pointsmall_detail->creator = $arg_array['creator'];
	            		$pointsmall_detail->editor = $arg_array['creator'];
	            	}
	            	
	            	$pointsmall_detail->promotionID = $promotionID;
	            	$pointsmall_detail->id = $k;
	            	$pointsmall_detail->name = $v['couponName'];
	            	$pointsmall_detail->points = $v['points'];
	            	$pointsmall_detail->pointsPrice = 0;
	            	$this->dbca->save($pointsmall_detail);
	            }
	            
    			//提交事务
	            $this->dbca->commit();
	            return array( 'code' => 200, 'message' => '保存成功' );
	            
    		} catch (Exception $e) {
    			
    			//回滚事务
	            $this->dbca->rollBack();
    			
	            if ($e->getCode() > 0) {
	            	return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
	            } else {
	            	error_log($e->getMessage());
	            	return array( 'code' => 500, 'message' => '系统错误' );
	            }
	            
    		}
    		
    		
    	} else if ($arg_array['type'] == 2) { //积分兑换
    		
    		$select_array = array(); //选择商品数组
    		
    		foreach ($arg_array as $key=>$value) {
    			if (substr($key,0,13) == 'row_exchange_') {
    				
    				$temp_arr = explode('_',$value);
    				
	    			if (count($temp_arr) != 3) {
	    				return array( 'code' => 400, 'message' => '参数错误' );
	    			}
	    			
	    			//$select_array[product_code] = 积分;
	    			$select_array[$temp_arr[0]] = array(
	    				'points' => $temp_arr[1],
	    				'bigCategoryID' => $temp_arr[2],
	    				'goodsName' => $arg_array['row_goodsName_exchange_'.$temp_arr[0]]
	    			);
    			}
    		}
    		
    		if (empty($select_array)) {
    			return array( 'code' => 400, 'message' => '请添加积分兑换的商品' );
    		}
    		
    		try {
    			
    			//开始事务
    			$this->dbca->beginTransaction();
    			
    			$pointsmall = new entity('promotion_pointsmall');
    			if ($flg == 3) { //编辑
    				
    				//获取促销ID
    				$promotionID = $arg_array['promotionID'];
    				
    				//查询促销是否存在
    				$pointsmall->promotionID = $arg_array['promotionID'];
    				if (!$this->dbca->fetch($pointsmall)) {
    					throw new Exception('该促销不存在', -1000);
    				}
    				$pointsmall->editor = $arg_array['creator'];
    			} else {
    				
    				//获取促销ID
    				$promotionID = $this->promotion_seq_no();
    				
    				$pointsmall->creator = $arg_array['creator'];
    				$pointsmall->editor = $arg_array['creator'];
    				$pointsmall->promotionID = $promotionID;
    			}
    			$pointsmall->promotionName = $arg_array['promotionName'];
    			$pointsmall->promotionIndex = $arg_array['promotionIndex'];
    			$pointsmall->startDate = $arg_array['startDate'];
    			$pointsmall->endDate = $arg_array['endDate'];
    			$pointsmall->type = $arg_array['type'];
    			$pointsmall->remark = $arg_array['remark'];
    			$pointsmall->useFlg = $arg_array['useFlg'];
    			$this->dbca->save( $pointsmall );
    			
    			//删除已有的促销详情
				$sql = 'DELETE FROM promotion_pointsmall_detail WHERE promotionID = ' . $promotionID;
            	$this->dbca->execute($sql);
    			
    			foreach ($select_array as $k=>$v) {
    				$pointsmall_detail = new entity('promotion_pointsmall_detail');
    				if ($flg == 3) {
    					$pointsmall_detail->editor = $arg_array['creator'];
    				} else {
    					$pointsmall_detail->creator = $arg_array['creator'];
    					$pointsmall_detail->editor = $arg_array['creator'];
    				}
    				$pointsmall_detail->promotionID = $promotionID;
    				$pointsmall_detail->id = $k;
    				$pointsmall_detail->name = $v['goodsName'];
    				$pointsmall_detail->bigCategoryID = $v['bigCategoryID'];
    				$pointsmall_detail->points = $v['points'];
    				$pointsmall_detail->pointsPrice = 0;
    				$this->dbca->save( $pointsmall_detail );
    			}
    			
    			//提交事务
    			$this->dbca->commit();
    			
    			return array( 'code' => 200, 'message' => '保存成功' );
    			
    		} catch ( Exception $e ) {
    			
    			//回滚事务
    			$this->dbca->rollBack();
    			
    			if ($e->getCode() > 0) {
	            	return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
	            } else {
	            	error_log($e->getMessage());
	            	return array( 'code' => 500, 'message' => '系统错误' );
	            }
    			
    		}
    		
    	} else if ( $arg_array['type'] == 3 ) { //积分换购商品
    		
    		$select_array = array(); //选择商品数组
    		
    		foreach ($arg_array as $key=>$value) {
    			if (substr($key,0,10) == 'row_trade_') {
    				
    				$temp_arr = explode('_',$value);
    				
	    			if (count($temp_arr) != 4) {
	    				return array( 'code' => 400, 'message' => '参数错误' );
	    			}
	    			
	    			//$select_array[product_code] = 积分;
	    			$select_array[$temp_arr[0]] = array(
	    						'points' => $temp_arr[1],
	    						'pointsPrice' => $temp_arr[2],
	    						'bigCategoryID' => $temp_arr[3],
	    						'goodsName' => $arg_array['row_goodsName_trade_'.$temp_arr[0]]
	    					);
    			}
    		}
    		
    		if (empty($select_array)) {
    			return array( 'code' => 400, 'message' => '请添加积分兑换的商品' );
    		}
    		
    		try {
    			
    			//开始事务
    			$this->dbca->beginTransaction();
    			
    			$pointsmall = new entity('promotion_pointsmall');
    			
    			if ($flg == 3) {
    				
    				//获取促销ID
    				$promotionID = $arg_array['promotionID'];
    				
    				//查询促销是否存在
    				$pointsmall->promotionID = $arg_array['promotionID'];
    				if (!$this->dbca->fetch($pointsmall)) {
    					throw new Exception('该促销不存在', -1000);
    				}
    				$pointsmall->editor = $arg_array['creator'];
    			} else {
    				
    				//获取促销ID
    				$promotionID = $this->promotion_seq_no();
    				
    				$pointsmall->creator = $arg_array['creator'];
    				$pointsmall->editor = $arg_array['creator'];
    				$pointsmall->promotionID = $promotionID;
    			}
    			
    			$pointsmall->promotionName = $arg_array['promotionName'];
    			$pointsmall->promotionIndex = $arg_array['promotionIndex'];
    			$pointsmall->startDate = $arg_array['startDate'];
    			$pointsmall->endDate = $arg_array['endDate'];
    			$pointsmall->type = $arg_array['type'];
    			$pointsmall->remark = $arg_array['remark'];
    			$pointsmall->useFlg = $arg_array['useFlg'];
    			$this->dbca->save( $pointsmall );
    			
    			//删除已有的促销详情
				$sql = 'DELETE FROM promotion_pointsmall_detail WHERE promotionID = ' . $promotionID;
            	$this->dbca->execute($sql);
    			
    			foreach ($select_array as $k=>$v) {
    				$pointsmall_detail = new entity('promotion_pointsmall_detail');
    				if ($flg == 3) {
    					$pointsmall_detail->editor = $arg_array['creator'];
    				} else {
    					$pointsmall_detail->creator = $arg_array['creator'];
    					$pointsmall_detail->editor = $arg_array['creator'];
    				}
    				$pointsmall_detail->promotionID = $promotionID;
    				$pointsmall_detail->id = $k;
    				$pointsmall_detail->name = $v['goodsName'];
    				$pointsmall_detail->bigCategoryID = $v['bigCategoryID'];
    				$pointsmall_detail->points = $v['points'];
    				$pointsmall_detail->pointsPrice = $v['pointsPrice'];
    				$this->dbca->save( $pointsmall_detail );
    			}
    			
    			//提交事务
    			$this->dbca->commit();
    			
    			return array( 'code' => 200, 'message' => '保存成功' );
    			
    		} catch ( Exception $e ) {
    			
    			//回滚事务
    			$this->dbca->rollBack();
    			
    			if ($e->getCode() > 0) {
	            	return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
	            } else {
	            	error_log($e->getMessage());
	            	return array( 'code' => 500, 'message' => '系统错误' );
    			}
    		}
    	}
    }
    
    /**保存积分兑换信息
     * @param $arg_array  参数数组
     * @return array
     * @throws Exception
     */
    public function savePointsConvertInfo( &$arg_array ){

        //参数检查
        if(!isset($arg_array['promotionID'] ,$arg_array['promotionName'],$arg_array['useFlg'],$arg_array['startDate'] ,$arg_array['endDate'],$arg_array['points'] , $arg_array['couponID']))
            return array( 'code' => 400, 'message' => '缺少参数' );

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        $promotionName = htmlspecialchars(trim($arg_array['promotionName'])) ;
        $startDate 	 = $arg_array['startDate'] ;
        $endDate   	 = $arg_array['endDate'] ;
        $useFlg  	 = $arg_array['useFlg'] ;
        $points  	 = $arg_array['points'] ;
        $couponID  	 = $arg_array['couponID'] ;
        $promotionID = $arg_array['promotionID'] ;
        $saveFlg = 1;    //区别保存或编辑的标志   1：保存   2：编辑

        //规则参数查检
        $error_msg = '' ;

        if($promotionName == '')
            $error_msg .= '促销活动名称不能为空</br>' ;

        if($startDate == '' || $endDate == '')
            $error_msg .= '促销开始和结束时间不能为空</br>' ;

        if($startDate > $endDate)
            $error_msg .= '促销开始时间不能大于结束时间</br>' ;

        if(!in_array($useFlg , array(0,1)))
            $error_msg .= '使用状态参数错误</br>';

        if( empty($couponID) )
            $error_msg .= '请选择优惠券</br>';

        if( !$commHandler->isInteger($points) || !is_numeric($points) )
            $error_msg .= '积分格式有误</br>';

        if( $error_msg != '' )
            return array( 'code' => 400, 'message' => $error_msg );

        try{

            //保存促销信息
            $save_promotion_points_coupon = new entity('promotion_points_coupon') ;

            if( $promotionID ){

                $saveFlg = 2;  //将标志置为2，表示编辑

                $save_promotion_points_coupon->promotionID = $promotionID;

                if( !$this->dbca->fetch($save_promotion_points_coupon) )
                    throw new Exception('没有找到积分兑换信息' , 404);

            }else{

                //生成促销活动号
                $promotionID = $this->promotion_seq_no() ;
                $save_promotion_points_coupon->promotionID = $promotionID;
                $save_promotion_points_coupon->creator    	 = $arg_array['creator'] ;

            }

            $couponObj = new entity('promotion_coupon');
            $couponObj->couponID = $arg_array['couponID'];

            if( !$this->dbca->fetch($couponObj) )
                throw new Exception('没有找到优惠券信息' , 404);

            $save_promotion_points_coupon->promotionName   	  	 = $arg_array['promotionName'] ;
            $save_promotion_points_coupon->startDate  	 = $arg_array['startDate'] ;
            $save_promotion_points_coupon->endDate	  	 = $arg_array['endDate'] ;
            $save_promotion_points_coupon->points		 = $arg_array['points'] ;
            $save_promotion_points_coupon->couponID		 = $arg_array['couponID'] ;
            $save_promotion_points_coupon->couponName    = $couponObj->couponName ;
            $save_promotion_points_coupon->useFlg		 = $useFlg;

            $this->dbca->save($save_promotion_points_coupon);

            if( $saveFlg == 1 ){
                return array( 'code'=>200 , 'message'=>'保存成功' );
            }else{
                return array( 'code'=>200 , 'message'=>'更新成功' );
            }

        } catch (Exception $e){

            if( $e->getCode() > 0 ){

                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );

            }else{
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询商品推荐信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
                            'sortname' => string 排序字段
                            'sortorder' => string 排序方式
                            'page' => int 分页页码
                            'rp' => int 分页页数
       )
     * @return null
     */
    public function searchGoodsRecommend( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //客户号
        if (isset($arg_array['recom_id']) && is_numeric($arg_array['recom_id'])) {
            $sql .= ' AND recom_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['recom_id'];
        }

        //商品编号
        if (isset($arg_array['product_code']) &&  !empty($arg_array['product_code']) ) {
            $sql .= ' AND product_code = ?';
            $params_type .= 's';
            $params_array[] = trim($arg_array['product_code']);
        }

        //有效期
        if (isset($arg_array['date']) &&  !empty($arg_array['date']) ) {
            $sql .= ' AND startDate <= ? AND endDate >= ?';
            $params_type .= 's';
            $params_type .= 's';
            $params_array[] = $arg_array['date'];
            $params_array[] = $arg_array['date'];
        }

        //状态 0:禁用 1:启用
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0 ,1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_recom ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM promotion_recom ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'creator' => $item->creator,
                    'createTime' => $item->createTime,
                    'recom_id' => $item->recom_id,
                    'product_code' => $item->product_code,
                    'mainPrice' => $item->mainPrice,
                    'useFlg' => $item->useFlg,
                    'startDate' => $item->startDate,
                    'endDate' => $item->endDate
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }
    /**
     * 查询商品推荐详细信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     *   )
     * @return null
     */
    public function searchGoodsRecommendDetail( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //推荐活动ID
        if (isset($arg_array['recom_id']) && is_numeric($arg_array['recom_id'])) {
            $sql .= ' AND recom_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['recom_id'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            //查询推荐商品信息
            $search_sql = 'SELECT * FROM promotion_recom_detail ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'creator' => $item->creator,
                    'createTime' => $item->createTime,
                    'recom_id' => $item->recom_id,
                    'product_code' => (string)$item->product_code,
                    'sale_price' => $item->sale_price
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 保存商品推荐信息 
     */
    public function  saveGoodsRecommend( $arg_array ){

        //实例化公共类
        $commHandler = new commHandler( $this->dbca );

        //实例化商品公共类
        $goodsHandler = new goodsHandler( $this->dbca );

        if( !isset( $arg_array['main_product_code'] , $arg_array['mainPrice'] , $arg_array['goodsInfo'] , $arg_array['operator'] ) )
            return array( 'code'=>400 , 'message'=>'参数错误' );

        if( empty($arg_array['main_product_code']) )
            return array( 'code'=>400 , 'message'=>'主商品编号不能为空' );

        //拆散主商品编码，检测是否是三级商品
        //$main = explode( '-' , $arg_array['main_product_code'] );
        //if( count($main) != 3 )
            //return array( 'code'=>400 , 'message'=>'主商品编号只能为三级商品编号' );

        //检查主商品信息
        $main_goods_array = array(	
        		'product_code' => $arg_array['main_product_code']
        	);
        $main_goods_search = $goodsHandler->searchGoodsSale($main_goods_array);

        if( empty($main_goods_search) )
            return array( 'code'=>404 , 'message'=>'主商品信息没有找到' );

        if( empty($arg_array['mainPrice']) ){
            return array( 'code'=>400 , 'message'=>'主商品组合价格不能为空' );
        }else{

            if( !$commHandler->isMoney($arg_array['mainPrice']) )
                return array( 'code'=>400 , 'message'=>'主商品组合价格格式有误' );

        }

        if( empty($arg_array['startDate']) || empty($arg_array['endDate']) )
            return array( 'code'=>400 , 'message'=>'有效期开始时间和结束时间不能为空' );

        if( $arg_array['startDate'] > $arg_array['endDate'] )
            return array( 'code'=>400 , 'message'=>'有效期开始时间不得大于结束时间' );

        if( empty($arg_array['goodsInfo']) )
            return array( 'code'=>400 , 'message'=>'组合商品不能为空' );

        //接收参数
        $main_product_code = $arg_array['main_product_code'];
        $goodsInfo         = $arg_array['goodsInfo'];
        $recom_id          = isset($arg_array['recom_id']) ? $arg_array['recom_id'] : NULL;
        $startDate         = $arg_array['startDate'];
        $endDate           = $arg_array['endDate'];
        $useFlg            = $arg_array['useFlg'];
        $mainPrice         = $arg_array['mainPrice'];
        $saveFlg           = 1; //区别保存和编辑的标志

        try{

            //开启事务
            $this->dbca->beginTransaction();

            $recommend_obj = new entity('promotion_recom');

            if( $recom_id ){

                $recommend_obj->recom_id = $recom_id;

                if( !$this->dbca->fetch($recommend_obj) )
                    throw new Exception( '没有找到信息' , 404 );

                $saveFlg = 2;

            }else{
                $recommend_obj->creator = $arg_array['operator'];
            }

            $recommend_obj->product_code = $main_product_code;
            $recommend_obj->mainPrice    = $mainPrice;
            $recommend_obj->useFlg       = $useFlg;
            $recommend_obj->startDate    = $startDate;
            $recommend_obj->endDate      = $endDate;

            $this->dbca->save( $recommend_obj );

            if( $recom_id ){

                //编辑时先删除之前的推荐商品
                $delSQL = 'DELETE FROM promotion_recom_detail WHERE recom_id = ?';
                $this->dbca->stmt_query( $delSQL , 'i' , $recom_id );

            }else{
                $recom_id = $this->dbca->insert_id;
            }

            foreach ( $goodsInfo as $info ){

                //检查组合商品信息
                $goods_array = array(	'product_code' => $info['product_code']);
                $goods_search = $goodsHandler->searchGoodsSale($goods_array);

                if( empty($goods_search) )
                    throw new Exception( '编号['.$info['product_code'].']的组合商品信息没有找到' , 404 );

                if( empty($info['sale_price']) ){
                    throw new Exception( '编号['.$info['product_code'].']的组合价格不能为空' , 400 );
                }else{

                    if( !$commHandler->isMoney($info['sale_price']) )
                        throw new Exception( '编号['.$info['product_code'].']的组合价格格式有误' , 400 );

                }

                if( $info['sale_price'] > $info['salePrice'] )
                    throw new Exception( '编号['.$info['product_code'].']的商品组合价格不得大于其商品价格' , 400 );

                $promotion_recom_detail = new entity('promotion_recom_detail');
                $promotion_recom_detail->creator = $arg_array['operator'];
                $promotion_recom_detail->recom_id = $recom_id;
                $promotion_recom_detail->product_code = $info['product_code'];
                $promotion_recom_detail->sale_price = $info['sale_price'];

                $this->dbca->save( $promotion_recom_detail );

            }

            //提交事务
            $this->dbca->commit();

            if( $saveFlg == 1 ){
                return array( 'code'=>200 , 'message'=>'保存成功' );
            }else{
                return array( 'code'=>200 , 'message'=>'修改成功' );
            }

        }catch (Exception $e){

            //回滚事务
            $this->dbca->rollBack();

            if( in_array( $e->getCode() , array(400,404,406) ) ){
                return array( 'code'=>$e->getCode() , 'message'=>$e->getMessage() );
            }else{
                error_log( $e->getMessage() );
                return array( 'code'=>500 , 'message'=>'系统错误，操作失败' );
            }

        }

    }

    public function getGoodsInfo($arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //推荐活动ID
        if (isset($arg_array['product_code']) && is_numeric($arg_array['product_code'])) {
            $sql .= ' AND product_code = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['product_code'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM goods_sale ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM goods_sale ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'goodsName'=>$item->goodsName,
                    'postID' => $item->postID,
                    'mainPostID' => $item->mainPostID,
                    'bigCategoryID' => $item->bigCategoryID,
                    'bigCategoryName' => $item->bigCategoryName,
                    'midCategoryID' => $item->product_code,
                    'midCategoryName' => $item->mainPrice,
                    'smallCategoryID' => $item->useFlg,
                    'smallCategoryName' => $item->startDate,
                    'forsale' => $item->forsale,
                    'product_code' => $item->product_code
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }
    
    /**
     * 检查添加商品在其他积分商城促销中是否已经使用过
     *
     */
    public function checkPointsMallGoods( $arg_array ) {
    	
    	if (!isset($arg_array['product_code'])) {
    		return array( 'code' => 400, 'message' => '请输入商品编码' );
    	}
    	
    	if (!isset($arg_array['startDate'],$arg_array['endDate']) || empty($arg_array['startDate']) || empty($arg_array['endDate'])) {
    		return array( 'code' => 400, 'message' => '请选择开始时间和结束时间' );
    	}
    	
    	if ($arg_array['startDate'] > $arg_array['endDate']) {
    		return array( 'code' => 400, 'message' => '开始时间必须小于结束时间' );
    	}
    	
    	//验证商品是否已经在其他促销中
    	
    	if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID'])) {
    		$sql = 'SELECT id FROM promotion_pointsmall_detail ppd JOIN 
					( SELECT promotionID FROM promotion_pointsmall 
					WHERE( promotionID != ? AND startDate >= ? AND startDate <= ?) 
					OR ( promotionID != ? AND endDate >= ? AND endDate <= ? ) 
					OR ( promotionID != ? AND startDate <= ? && endDate >= ? ) ) T_g
					ON ppd.promotionID = T_g.promotionID';
    		$types = 'issississ';
    		$params = array(
    			$arg_array['promotionID'],
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['promotionID'],
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['promotionID'],
    			$arg_array['startDate'],
    			$arg_array['endDate']
    		);
    		
    	} else {
    		$sql = 'SELECT id FROM promotion_pointsmall_detail ppd JOIN 
					( SELECT promotionID FROM promotion_pointsmall WHERE (startDate >= ? AND startDate <= ?) OR ( endDate >= ? AND endDate <= ? ) OR ( startDate <= ? && endDate >= ? ) ) T_g
					ON ppd.promotionID = T_g.promotionID';
    		$types = 'ssssss';
    		$params = array(
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['startDate'],
    			$arg_array['endDate']
    		);
    	}
    	$product_code_result = $this->dbca->stmt_query($sql,$types,$params);
    	
    	$product_code_array = array();
    	if ($product_code_result) {
    		foreach ($product_code_result as $product_code) {
    			$product_code_array[] = $product_code->id;
    		}
    	}
    	
    	if (in_array($arg_array['product_code'],$product_code_array)) {
    		return array( 'code' => 300, 'message' => '该商品在积分商城的其他促销中已经使用');
    	} else {
    		return array( 'code' => 200, 'message' => '该商品在积分商城的其他促销中没有使用');
    	}
    	
    }
    
    /**
     * 检查优惠券有效性
     *
     */
    public function checkPointsMallCoupon( $arg_array ){
    	
    	if (!isset($arg_array['couponID']) || !is_numeric($arg_array['couponID'])) {
    		return array( 'code' => 400, 'message' => '参数错误' );
    	}
    	
    	if (!isset($arg_array['startDate'],$arg_array['endDate']) || empty($arg_array['startDate']) || empty($arg_array['endDate'])) {
    		return array( 'code' => 400, 'message' => '请选择开始时间和结束时间' );
    	}
    	
    	if ($arg_array['startDate'] > $arg_array['endDate']) {
    		return array( 'code' => 400, 'message' => '开始时间必须小于结束时间' );
    	}
    	
    	$sql = 'SELECT couponID,couponName FROM promotion_coupon WHERE couponID = ? AND couponType=2 AND startDate<=? AND endDate>=?';
    	$accountCoupon = $this->dbca->stmt_query( $sql ,'iss' , array( $arg_array['couponID'], $arg_array['sys_datatime'],$arg_array['sys_datatime']));
    	if (!$accountCoupon) {
    		return array( 'code' => 400, 'message' => '该优惠券已过期' );
    	}
    	
    	if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID'])) {
    		$sql = 'SELECT id FROM promotion_pointsmall_detail ppd JOIN 
					( SELECT promotionID FROM promotion_pointsmall 
					WHERE( promotionID != ? AND startDate >= ? AND startDate <= ?) 
					OR ( promotionID != ? AND endDate >= ? AND endDate <= ? ) 
					OR ( promotionID != ? AND startDate <= ? && endDate >= ? ) ) T_g
					ON ppd.promotionID = T_g.promotionID';
    		$types = 'issississ';
    		$params = array(
    			$arg_array['promotionID'],
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['promotionID'],
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['promotionID'],
    			$arg_array['startDate'],
    			$arg_array['endDate']
    		);
    		
    	} else {
    		$sql = 'SELECT id FROM promotion_pointsmall_detail ppd JOIN 
					( SELECT promotionID FROM promotion_pointsmall WHERE (startDate >= ? AND startDate <= ?) OR ( endDate >= ? AND endDate <= ? ) OR ( startDate <= ? && endDate >= ? ) ) T_g
					ON ppd.promotionID = T_g.promotionID';
    		$types = 'ssssss';
    		$params = array(
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['startDate'],
    			$arg_array['endDate'],
    			$arg_array['startDate'],
    			$arg_array['endDate']
    		);
    	}
    	$product_code_result = $this->dbca->stmt_query($sql,$types,$params);
    	
    	$product_code_array = array();
    	if ($product_code_result) {
    		foreach ($product_code_result as $product_code) {
    			$product_code_array[] = $product_code->id;
    		}
    	}
    	
    	if (in_array($arg_array['couponID'],$product_code_array)) {
    		return array( 'code' => 300, 'message' => '该优惠券在积分商城的其他促销中已经使用');
    	} else {
    		return array( 'code' => 200, 'message' => '该优惠券在积分商城的其他促销中没有使用');
    	}
    	
    	
    }
    
	/**
	 * 查找积分商城商品展示区
	 *
	 */
	public function searchPointsMallInit() {
		
		$item_array = array(
			'coupon' => array(), //积分换券
			'goods' => array(), //积分商品
			'category' => array() //商品分类
		);
		
		//当前日期
		$date = date(G_DEFAULT_DATETIME_FORMAT);
		
		$arg_mall_array = array(
			'startDate' => $date
		);
		$mall_array = $this->searchPointsMall( $arg_mall_array );
		
		//组织积分商城促销活动
		if ($mall_array) {
			foreach ($mall_array as &$mall) {
				
				//更多链接
				$mall['more'] = '/shop/pointsMall-0-'.$mall['promotionID'].'-0-0-1-sale-desc-1.html';
				
				if ($mall['type'] == 1) { //积分换券
					$item_array['coupon'][$mall['promotionID']] = $mall;
				} else if (in_array($mall['type'],array(2,3))) { //积分兑换、积分换购
					$item_array['goods'][$mall['promotionID']] = $mall;
				}
			}
		}
		
		
		//查询组织积分商城促销活动详情
		if ($item_array) {
			foreach ($item_array as $key=>$value) {
				
				foreach ($value as $k=>$v) {
					$arg_detail_array = array(
						'promotionID' => $v['promotionID'],
						'rp' => 5
					);
					
					if ($v['type'] == 1) {
						
						//查询券详情
						$item_detail_array = $this->searchPointsCouponDetail( $arg_detail_array );
						
					} else if (in_array($v['type'],array(2,3))) {
						
						//查询商品详情
						$item_detail_array = $this->searchPointsGoodsDetail( $arg_detail_array );
						
						//查询商品分类
						$item_goods_category = $this->searchPointsGoodsCategory( $arg_detail_array );
					}
					
					if (isset($item_goods_category) && !empty($item_goods_category)) {
						foreach ($item_goods_category as $list) {
							$item_array['category'][$list['bigCategoryID']] = array(
										'link' => '/shop/pointsMall-'.$list['bigCategoryID'].'-0-0-0-1-sale-desc-1.html',
										'description' => $list['description']
									);
						}
					}
					
					$item_array[$key][$v['promotionID']]['detail'] = $item_detail_array;
					$item_array[$key][$v['promotionID']]['count'] = $arg_detail_array['count'];
				}
				
			}
		}
		
		return $item_array;
		
	}
	
	/**
     * 查询积分商城商品分类[商品]
     */
    public function searchPointsGoodsCategory( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';
		
        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND ppd.promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
		
        try {

            //查询分类信息
            $search_sql = 'SELECT distinct(gb.bigCategoryID),gb.description FROM promotion_pointsmall_detail ppd JOIN goods_bigcategory gb
            				ON ppd.bigCategoryID = gb.bigCategoryID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'bigCategoryID'  => $item->bigCategoryID,
                    'description'  => $item->description
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }
    }
	/**
     * 查询积分商城促销详情[商品]
     */
    public function searchPointsGoodsDetail( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND ppd.promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }
        
        //活动时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
        	$sql .= ' AND pp.startDate <= ? AND pp.endDate >= ?';
        	$params_type .= 'ss';
        	$params_array[] = $arg_array['startDate'];
        	$params_array[] = $arg_array['startDate'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
		
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_pointsmall pp
                				JOIN promotion_pointsmall_detail ppd ON pp.promotionID = ppd.promotionID
                 				JOIN goods_sale gs ON ppd.id = gs.product_code ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT ppd.*,gs.* FROM promotion_pointsmall pp
            				JOIN promotion_pointsmall_detail ppd ON pp.promotionID = ppd.promotionID
            				JOIN goods_sale gs
            				ON ppd.id = gs.product_code ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'promotionID'  => $item->promotionID,
                    'id'  => $item->id,
                    'name' => $item->name,
                    'points'  => $item->points,
                    'pointsPrice'  => $item->pointsPrice,
                    'link' => G_WEBSITE_DOMAINNAME . '/shop/goods-' . $item->postID . '.html',
                    'img_link' => G_IMAGE_URL . '/goods/' . $item->goodsMainPic,
                    'goodsName' => $item->goodsName
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }
    /**
     * 查询积分商城促销详情[优惠券]
     */
    public function searchPointsCouponDetail( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND ppd.promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
        
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_pointsmall_detail ppd
                 				JOIN promotion_coupon pc ON ppd.id = pc.couponID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT ppd.*,pc.* FROM promotion_pointsmall_detail ppd 
            				JOIN promotion_coupon pc ON ppd.id = pc.couponID ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array)
                return null;
			
            foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'promotionID'  => $item->promotionID,
                    'id'  => $item->id,
                    'name' => $item->name,
                    'points'  => $item->points,
                    'pointsPrice'  => $item->pointsPrice,
                    'img_link' => G_THEME_IMAGE_URL . '/comm/lppz.jpg' //默认优惠券图片
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }

    }
    
    /**
     * 积分商城列表页商品查询
     *
     */
    public function searchPointsMallByParams( &$arg_array ){
    	
    	//sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID']) && $arg_array['promotionID']>0) {
            $sql .= ' AND ppd.promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }
        
        //分类ID
        if (isset($arg_array['cid']) && is_numeric($arg_array['cid']) && $arg_array['cid']>0) {
        	$sql .= ' AND ppd.bigCategoryID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cid'];
        }
        
        //活动时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
        	$sql .= ' AND pp.startDate <= ?';
        	$sql .= ' AND pp.endDate >= ?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'];
            $params_array[] = $arg_array['startDate'];
        }
        
        //积分范围
        if (isset($arg_array['range']) && in_array($arg_array['range'],array(2,3,4,5,6,7,8,9,10))) {
        	$sql .= ' AND ppd.points >= ? AND ppd.points < ? ';
            $params_type .= 'ii';
            
        	switch ($arg_array['range']) {
        		case 2:
        			$params_array[] = 100; $params_array[] = 200;
		            break;
		        case 3:
        			$params_array[] = 200; $params_array[] = 300;
		            break;
		       	case 4:
        			$params_array[] = 300; $params_array[] = 400;
		            break;
		       	case 5:
        			$params_array[] = 400; $params_array[] = 500;
		            break;
		        case 6:
        			$params_array[] = 500; $params_array[] = 600;
		            break;
		       	case 7:
        			$params_array[] = 600; $params_array[] = 700;
		            break;
		        case 8:
        			$params_array[] = 700; $params_array[] = 800;
		            break;
		        case 9:
        			$params_array[] = 800; $params_array[] = 900;
		            break;
		       	case 10:
        			$params_array[] = 900; $params_array[] = 1000;
		            break;
        	}
        } else if (isset($arg_array['range']) && in_array($arg_array['range'],array(1,11))) {
        	if ($arg_array['range'] == 1) {
        		$sql .= ' AND ppd.points < ? ';
	            $params_type .= 'i';
	            $params_array[] = 100;
        	} else if ($arg_array['range'] == 11) {
        		$sql .= ' AND ppd.points > ? ';
	            $params_type .= 'i';
	            $params_array[] = 1000;
        	}
        	
        }
        
        //我能兑换的积分
        if (isset($arg_array['points']) && $arg_array['points'] == 1) {
			$sql .= ' AND ppd.points <= ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['account'];
        }
        
        //排序
        if (isset($arg_array['sortby']) && in_array($arg_array['sortby'],array('update','sale','price','discount'))) {
        	switch ($arg_array['sortby']){
        		case 'update':
        			$arg_array['sortname'] = 'createTime';
        			break;
        		case 'price':
        			$arg_array['sortname'] = 'points';
        			break;
        	}
        }
		
        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
		        
        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {
				
                //统计数量
                if (isset($arg_array['type']) && $arg_array['type'] == 1) {
                	$search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_pointsmall pp
                					JOIN promotion_pointsmall_detail ppd ON pp.promotionID = ppd.promotionID
	                				JOIN promotion_coupon pc ON ppd.id = pc.couponID ' . $sql;
                } else {
	                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_pointsmall pp
	                				JOIN promotion_pointsmall_detail ppd ON pp.promotionID = ppd.promotionID
	                				JOIN goods_sale gs ON ppd.id = gs.product_code ' . $sql;
                }
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY ppd.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY ppd.%s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }
			
            //查询分类信息
            if (isset($arg_array['type']) && $arg_array['type'] == 1) {
            	$search_sql = 'SELECT ppd.*,pc.* FROM promotion_pointsmall pp
            				JOIN promotion_pointsmall_detail ppd ON pp.promotionID = ppd.promotionID
            				JOIN promotion_coupon pc ON ppd.id = pc.couponID ' . $sql;
            	
            	$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
	            if (!$temp_item_array)
	                return null;
	
	            foreach($temp_item_array as &$item) {
	                $item_array[] = array(
	                    'promotionID'  => $item->promotionID,
	                    'id'  => $item->id,
	                    'name' => $item->name,
	                    'points'  => $item->points,
	                    'pointsPrice'  => $item->pointsPrice,
	                    'couponName' => $item->couponName,
	                    'img_link' => G_THEME_IMAGE_URL . '/comm/lppz.jpg' //默认优惠券图片
	                );
	            }
            } else {
            	$search_sql = 'SELECT ppd.*,gs.* FROM promotion_pointsmall pp
            				JOIN promotion_pointsmall_detail ppd ON pp.promotionID = ppd.promotionID
            				JOIN goods_sale gs ON ppd.id = gs.product_code ' . $sql;
            	$temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
	            if (!$temp_item_array)
	                return null;
	
	            foreach($temp_item_array as &$item) {
	                $item_array[] = array(
	                    'promotionID'  => $item->promotionID,
	                    'id'  => $item->id,
	                    'name' => $item->name,
	                    'points'  => $item->points,
	                    'pointsPrice'  => $item->pointsPrice,
	                    'link' => G_WEBSITE_DOMAINNAME . '/shop/goods-' . $item->postID . '.html',
	                    'img_link' => G_IMAGE_URL . '/goods/' . $item->goodsMainPic,
	                    'goodsName' => $item->goodsName
	                );
	            }
            }
			
            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;


        }
    	
    }
    
    /**
     * 验证并获取积分商城商品
     *
     */
    public function validPointsMallGoods( $arg_array ){
    	
    	if (!isset($arg_array['id'])) {
    		return array( 'code' => 400, 'message' => '请输入商品编码' );
    	}
    	
    	if (!isset($arg_array['startDate'])) {
    		return array( 'code' => 400, 'message' => '请输入活动时间' );
    	}
    	
    	//sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();
    	
    	//使用状态标志
        if ( isset($arg_array['id']) ) {
            $sql .= ' AND ppd.id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['id'];
        }

        //促销日期
        if (isset($arg_array['startDate']) && trim($arg_array['startDate']) != '') {
            $sql .= ' AND pp.startDate <=? AND pp.endDate >=?';
            $params_type .= 'ss';
            $params_array[] = $arg_array['startDate'] ;
            $params_array[] = $arg_array['startDate'] ;
        }
        
        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }
        
        try {
        	
        	$sql = 'SELECT ppd.* FROM promotion_pointsmall pp 
						JOIN promotion_pointsmall_detail ppd ON pp.promotionID = ppd.promotionID ' . $sql;
        	
        	$temp_item_array = $this->dbca->stmt_query( $sql, $params_type, $params_array );
            if (!$temp_item_array) {
                return null;
            }
        	
        	foreach($temp_item_array as &$item) {
                $item_array[] = array(
                    'promotionID'  => $item->promotionID,
                    'id'  => $item->id,
                    'name' => $item->name,
                    'points'  => $item->points,
                    'pointsPrice'  => $item->pointsPrice
                );
            }
        	
        	return $item_array;
        	
        } catch (Exception $e) {
        	
        	error_log($e->getMessage());
            return null;
            
        }
    	
    	
    }

    /**
     * 微信互动活动保存
     * @param $arg_array
     */
    public function saveWxActivity(&$arg_array){

        if(!isset($arg_array['dt']['promotion_Name']) || empty($arg_array['dt']['promotion_Name'])){
            return array('code'=>400,'message'=>'标题不能为空');
        }
        if(!isset($arg_array['dt']['promotion_Type']) || empty($arg_array['dt']['promotion_Type'])){
            return array('code'=>400,'message'=>'请选择活动类型');
        }
        if(!isset($arg_array['dt']['start_Date']) || empty($arg_array['dt']['start_Date'])){
            return array('code'=>400,'message'=>'请选择开始时间');
        }
        if(!isset($arg_array['dt']['end_Date']) || empty($arg_array['dt']['end_Date'])){
            return array('code'=>400,'message'=>'请选择结束时间');
        }

        if($arg_array['dt']['end_Date']<$arg_array['dt']['start_Date']){
            return array('code'=>400,'message'=>'开始时间不能大于结束时间');
        }

        if(!isset($arg_array['dt']['participateTime']) || !is_numeric($arg_array['dt']['participateTime'])){
            return array('code'=>400,'message'=>'请输入正确最大次数');
        }

        if(!isset($arg_array['dt']['acceptEndDate']) || empty($arg_array['dt']['acceptEndDate'])){
            return array('code'=>400,'message'=>'请选择领奖结束日期');
        }

        if(!isset($arg_array['datacache']) || count($arg_array['datacache']) == 0){
            return array('code'=>400,'message'=>'请设置奖项');
        }

        if($arg_array['addRate']>100){
            return array('code'=>400,'message'=>'奖项设置概率之和不能大于100%');
        }

        try {
            $num = 0;
            $promotion_weixin_check = $this->dbca->stmt_query('select count(*) as num from promotion_weixin where startDate >= ? and startDate <= ? and useFlg = ? and promotionType = ? ','ssii',array($arg_array['dt']['start_Date'],$arg_array['dt']['end_Date'],1,$arg_array['dt']['promotion_Type']));
            $num += $promotion_weixin_check[0]->num;
            $promotion_weixin_checkone = $this->dbca->stmt_query('select count(*) as num from promotion_weixin where startDate<=? and endDate >=? and useFlg = ? and promotionType = ? ','ssii',array($arg_array['dt']['start_Date'],$arg_array['dt']['start_Date'],1,$arg_array['dt']['promotion_Type']));
            $num += $promotion_weixin_checkone[0]->num;

            if($num>0){
                return array('code'=>400,'message'=>'在 ['.$arg_array['dt']['start_Date'].' ~ '.$arg_array['dt']['end_Date'].'] 时间段内有重复活动');
            }

            $promotionID = $this->promotion_seq_no();

            $promotion_weixin = new entity('promotion_weixin');
            $promotion_weixin->creator = $arg_array['creator'];
            $promotion_weixin->promotionID = $promotionID;
            $promotion_weixin->promotionName = $arg_array['dt']['promotion_Name'];
            $promotion_weixin->promotionType = $arg_array['dt']['promotion_Type'];
            $promotion_weixin->startDate = $arg_array['dt']['start_Date'];
            $promotion_weixin->endDate = $arg_array['dt']['end_Date'];
            $promotion_weixin->totalTime = $arg_array['dt']['totalTime'];
            $promotion_weixin->participateTime = $arg_array['dt']['participateTime'];
            $promotion_weixin->isPointsExchange = $arg_array['dt']['is_PointsExchange'];
            $promotion_weixin->maxExchangeTime = $arg_array['dt']['maxExchangeTime'];
            $promotion_weixin->points = $arg_array['dt']['point'];
            $promotion_weixin->acceptEndDate = $arg_array['dt']['acceptEndDate'];
            $promotion_weixin->useFlg = 1;
            $this->dbca->save($promotion_weixin);

            foreach($arg_array['datacache'] as $val){
                $promotion_weixin_detail = new entity('promotion_weixin_detail');
                $promotion_weixin_detail->creator = $arg_array['creator'];
                $promotion_weixin_detail->promotionID = $promotionID;
                $promotion_weixin_detail->awardsName = $val[0];
                $promotion_weixin_detail->awardsRatio = $val['awardsRatio'];
                $promotion_weixin_detail->awardsRate = $val['awardsRate'];
                $promotion_weixin_detail->prize= $val[2];
                $promotion_weixin_detail->prizeNum = $val[3];
                $this->dbca->save($promotion_weixin_detail);

                $insert_id = $this->dbca->insert_id;

                //保存所有微信奖项中奖随机数
                foreach($val['randNum'] as $valNum){

                    $weixin_awards_random = new entity('promotion_weixin_awards_random');
                    $weixin_awards_random->creator = $arg_array['creator'];
                    $weixin_awards_random->awardsID = $insert_id;
                    $weixin_awards_random->random_num = $valNum;

                    $this->dbca->save($weixin_awards_random);
                }

            }

            return array('code'=>200,'message'=>'微信互动活动保存成功');

        }catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 微信互动活动编辑
     * @param $arg_array
     * @return array|null
     */
    public function editWxActivity(&$arg_array){

        if(!isset($arg_array['dt']['promotion_Name']) || empty($arg_array['dt']['promotion_Name'])){
            return array('code'=>400,'message'=>'标题不能为空');
        }
        if(!isset($arg_array['dt']['promotion_Type']) || empty($arg_array['dt']['promotion_Type'])){
            return array('code'=>400,'message'=>'请选择活动类型');
        }
        if(!isset($arg_array['dt']['start_Date']) || empty($arg_array['dt']['start_Date'])){
            return array('code'=>400,'message'=>'请选择开始时间');
        }
        if(!isset($arg_array['dt']['end_Date']) || empty($arg_array['dt']['end_Date'])){
            return array('code'=>400,'message'=>'请选择结束时间');
        }

        if($arg_array['dt']['end_Date']<$arg_array['dt']['start_Date']){
            return array('code'=>400,'message'=>'开始时间不能大于结束时间');
        }

        if(!isset($arg_array['dt']['participateTime']) || !is_numeric($arg_array['dt']['participateTime'])){
            return array('code'=>400,'message'=>'请输入正确最大次数');
        }

        if(!isset($arg_array['dt']['acceptEndDate']) || empty($arg_array['dt']['acceptEndDate'])){
            return array('code'=>400,'message'=>'请选择领奖结束日期');
        }

        if(!isset($arg_array['datacache']) || count($arg_array['datacache']) == 0){
            return array('code'=>400,'message'=>'请设置奖项');
        }

        if($arg_array['addRate']>1){
            return array('code'=>400,'message'=>'奖项设置概率之和不能大于100%');
        }

        try {
            $num = 0;
            $promotion_weixin_check = $this->dbca->stmt_query('select count(*) as num from promotion_weixin where  promotionID !=? and startDate >= ? and startDate <= ? and useFlg = ? and promotionType= ?  ','issii',array($arg_array['promotionID'],$arg_array['dt']['start_Date'],$arg_array['dt']['end_Date'],1,$arg_array['dt']['promotion_Type']));
            $num += $promotion_weixin_check[0]->num;
            $promotion_weixin_checkone = $this->dbca->stmt_query('select count(*) as num from promotion_weixin where promotionID !=? and startDate<=? and endDate >=? and useFlg = ? and promotionType= ? ','issii',array($arg_array['promotionID'],$arg_array['dt']['start_Date'],$arg_array['dt']['start_Date'],1,$arg_array['dt']['promotion_Type']));
            $num += $promotion_weixin_checkone[0]->num;

            if($num>0){
                return array('code'=>400,'message'=>'在['.$arg_array['dt']['start_Date'].'~'.$arg_array['dt']['end_Date'].']时间段内有重复活动');
            }

            $promotion_weixin = new entity('promotion_weixin');
            $promotion_weixin->promotionID = $arg_array['promotionID'];

            if($this->dbca->fetch($promotion_weixin)){
                $promotion_weixin->creator = $arg_array['creator'];
                $promotion_weixin->promotionName = $arg_array['dt']['promotion_Name'];
                $promotion_weixin->promotionType = $arg_array['dt']['promotion_Type'];
                $promotion_weixin->startDate = $arg_array['dt']['start_Date'];
                $promotion_weixin->endDate = $arg_array['dt']['end_Date'];
                $promotion_weixin->totalTime = $arg_array['dt']['totalTime'];
                $promotion_weixin->participateTime = $arg_array['dt']['participateTime'];
                $promotion_weixin->isPointsExchange = $arg_array['dt']['is_PointsExchange'];
                $promotion_weixin->maxExchangeTime = $arg_array['dt']['maxExchangeTime'];
                $promotion_weixin->points = $arg_array['dt']['point'];
                $promotion_weixin->acceptEndDate = $arg_array['dt']['acceptEndDate'];
                $this->dbca->save($promotion_weixin);
            }else{
                return array('code'=>400,'message'=>'活动不存在');
            }

            $weixin_detail = $this->dbca->stmt_query('select * from promotion_weixin_detail where promotionID = ?','i',$arg_array['promotionID']);

            //删除所有奖项中奖随机数
            foreach($weixin_detail as $val){
                $this->dbca->stmt_query('delete from promotion_weixin_awards_random where awardsID = ?','i',$val->awardsID);
            }

            //删除所有微信促销活动奖项设置
            $this->dbca->stmt_query('delete from promotion_weixin_detail where promotionID = ?','i',$arg_array['promotionID']);

            foreach($arg_array['datacache'] as $val){
                //保存所有微信促销活动奖项设置
                $promotion_weixin_detail = new entity('promotion_weixin_detail');
                $promotion_weixin_detail->creator = $arg_array['creator'];
                $promotion_weixin_detail->promotionID = $arg_array['promotionID'];
                $promotion_weixin_detail->awardsName = $val[0];
                $promotion_weixin_detail->awardsRatio = $val['awardsRatio'];
                $promotion_weixin_detail->awardsRate = $val['awardsRate'];
                $promotion_weixin_detail->prize= $val[2];
                $promotion_weixin_detail->prizeNum = $val[3];
                $this->dbca->save($promotion_weixin_detail);

                $insert_id = $this->dbca->insert_id;


                //保存所有微信奖项中奖随机数
                foreach($val['randNum'] as $valNum){

                    $weixin_awards_random = new entity('promotion_weixin_awards_random');
                    $weixin_awards_random->creator = $arg_array['creator'];
                    $weixin_awards_random->awardsID = $insert_id;
                    $weixin_awards_random->random_num = $valNum;

                    $this->dbca->save($weixin_awards_random);
                }

            }

            return array('code'=>200,'message'=>'微信互动活动保存成功');

        }catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }


    /**
     * 查询微信互动活动
     * @param $arg_array
     * @return array|null
     */
    public function searchWxActivity( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //活动类型
        if (isset($arg_array['promotionType']) && is_numeric($arg_array['promotionType'])) {
            $sql .= ' AND promotionType = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionType'];
        }

        //活动名称
        if (isset($arg_array['promotionName']) && !empty($arg_array['promotionName'])) {
            $sql .= ' AND promotionName like ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['promotionName'] . '%';
        }

        //开始日期
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND startDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        //结束日期
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate']) ) {
            $sql .= ' AND endDate >= ? ';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        //是否可使用积分换次数
        if (isset($arg_array['isPointsExchange']) && in_array($arg_array['isPointsExchange'],array(0,1))) {
            $sql .= ' AND isPointsExchange = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['isPointsExchange'];
        }

        //使用状态
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'],array(0,1))) {
            $sql .= ' AND useFlg = ? ';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }


        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_weixin  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_weixin ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    switch($item->promotionType) {
                        case 1:
                            $item->promotionTypeName = '刮刮卡';
                            break;
                        case 2:
                            $item->promotionTypeName = '摇一摇';
                            break;
                        case 3:
                            $item->promotionTypeName = '大转盘';
                            break;
                        case 4:
                            $item->promotionTypeName = '盖高楼';
                            break;
                        case 5:
                            $item->promotionTypeName = '接红包';
                            break;
                        default:
                            $item->promotionTypeName = '无';
                            break;
                    }

                    $item_array[] = array(
                        'createTime' => $item->createTime,                //创建时间
                        'promotionID' => $item->promotionID,            //活动ID
                        'promotionName' => $item->promotionName,            //活动名称
                        'promotionType' => $item->promotionType,            //活动类型
                        'promotionTypeName' => $item->promotionTypeName,            //活动类型名称
                        'startDate' => $item->startDate,        //开始日期
                        'endDate' => $item->endDate,              //结束日期
                        'totalTime' => $item->totalTime,        //每人最多参与抽奖次数
                        'participateTime' => $item->participateTime,        //每天最多抽奖次数
                        'isPointsExchange' => $item->isPointsExchange,                //是否可使用积分换次数
                        'points' => $item->points,        //扣除积分
                        'maxExchangeTime' => $item->maxExchangeTime,            //最多可换的次数
                        'acceptEndDate' => $item->acceptEndDate,            //领奖结束日期
                        'useFlg' => $item->useFlg,            //使用状态
                        'useFlgName' => $item->useFlg ? '启用' : '禁用',           //使用状态
                        'pv' => $item->pv
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 更新微信促销活动pv
     * @param $promotionID
     * @return bool
     */
    public function updateWxActivityPV( $promotionID ) {

        if ( !isset($promotionID) || !is_numeric($promotionID) || $promotionID <=0 ) {
            return false;
        }
        $update_sql = 'UPDATE promotion_weixin SET pv = pv + 1 WHERE promotionID = ?';
        return $this->dbca->stmt_query($update_sql, 'i', $promotionID);

    }

    /**
     * 查询微信互动活动（奖项）
     * @param $arg_array
     * @return array|null
     */
    public function searchWxActivityDetail( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_weixin_detail  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_weixin_detail ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'promotionID' => $item->promotionID,
                        'awardsID' => $item->awardsID,
                        'awardsName' => $item->awardsName,
                        'awardsRate' => $item->awardsRate,
                        'awardsRatio' => $item->awardsRatio,
                        'prize' => $item->prize,
                        'prizeNum' => $item->prizeNum,
                        'alreadyGetNum' => $item->alreadyGetNum
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }


    /**
     * 查询微信互动活动（奖项）
     * @param $arg_array
     * @return array|null
     */
    public function searchWxActivityAwardsRandom( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动ID
        $sql .= ' AND awardsID = ?';
        $params_type .= 'i';
        $params_array[] = $arg_array['awardsID'];

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_weixin_awards_random ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = $item->random_num;
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 查询微信互动活动（抽奖记录）
     * @param $arg_array
     * @return array|null
     */
    public function searchWxActivityLog( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //抽奖日期
        if (isset($arg_array['useDate']) && !empty($arg_array['useDate'])) {
            $sql .= ' AND useDate = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['useDate'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_weixin_log  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_weixin_log ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            foreach ($temp_item_array as &$item) {
                $item_array[] = array(
                    'createTime' => $item->createTime,                //创建时间
                    'promotionID' => $item->promotionID,            //活动ID
                    'pcustID' => $item->pcustID,            //会员号
                    'useDate' => $item->useDate            //抽奖日期
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 微信互动活动(保存领取记录)
     * @param $arg_array
     */
    public function saveWxActivityLog( $arg_array ) {

        $log_obj = new entity('promotion_weixin_log');
        $log_obj->creator = 'system';
        $log_obj->promotionID = $arg_array['promotionID'];
        $log_obj->pcustID = $arg_array['pcustID'];
        $log_obj->useDate = $arg_array['useDate'];
        $this->dbca->save($log_obj);

    }

    /**
     * 查询微信互动活动（会员奖品）
     * @param $arg_array
     * @return array|null
     */
    public function searchCustomerWxPrize( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //促销活动ID
        if (isset($arg_array['promotionID']) && is_numeric($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //是否已领取奖品
        if (isset($arg_array['isReceive']) && in_array($arg_array['isReceive'], array(0, 1))) {
            $sql .= ' AND isReceive = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isReceive'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_weixin_prize  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询备注信息
            $search_sql = 'SELECT * FROM promotion_weixin_prize ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'uuid' => $item->uuid,                //uuid
                        'createTime' => $item->createTime,                //创建时间
                        'promotionID' => $item->promotionID,            //活动ID
                        'pcustID' => $item->pcustID,            //会员号
                        'awardsID' => $item->awardsID,            //奖项ID
                        'awardsName' => $item->awardsName,            //奖项名
                        'prize' => $item->prize,            //奖品
                        'isReceive' => $item->isReceive,            //是否已领取奖品
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    /**
     * 微信互动活动(保存会员领取礼品)
     * @param $arg_array
     */
    public function saveCustomerReceivePrize( $arg_array ) {

        //实例公共类
        $commHandler = new commHandler();

        /**
         * =================================
         * 检查参数
         * =================================
         */
        if (!isset($arg_array['pcustID'], $arg_array['custName'], $arg_array['mobile'], $arg_array['address'], $arg_array['identityCard'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!is_numeric($arg_array['pcustID']) || $arg_array['pcustID'] <= 0) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (empty($arg_array['custName'])) {
            return array( 'code' => 400, 'message' => '收货人不能为空' );
        }
        if (!$commHandler->isMobile($arg_array['mobile'])) {
            return array( 'code' => 400, 'message' => '手机号码填写错误，格式：18612345678' );
        }
        if (empty($arg_array['address'])) {
            return array( 'code' => 400, 'message' => '收货地址不能为空' );
        }
        /**
         * =================================
         * 检查参数
         * =================================
         */

        try {

            $this->dbca->beginTransaction();

            //查询会员奖品
            $temp_arg_array = array(
                'pcustID' => $arg_array['pcustID'],
                'isReceive' => 0
            );
            $cust_award_array = $this->searchCustomerWxPrize( $temp_arg_array );
            if (!$cust_award_array) {
                throw new Exception('您的奖品已经领取成功，我们会尽快给您送到家，请放心啦！', 404);
            }

            //生成奖品数组，并更新会员奖品为已领取
            $prize_array = array();
            foreach($cust_award_array as &$award) {

                $update_sql = 'UPDATE promotion_weixin_prize SET isReceive = 1 WHERE uuid = \'' . $award['uuid'] . '\'';
                $this->dbca->execute($update_sql);

                $prize_array[] = $award['prize'];

            }

            $receive_prize_obj = new entity('promotion_weixin_receive_prize');
            $receive_prize_obj->creator = 'system';
            $receive_prize_obj->pcustID = $arg_array['pcustID'];
            $receive_prize_obj->custName = $arg_array['custName'];
            $receive_prize_obj->mobile = $arg_array['mobile'];
            $receive_prize_obj->address = $arg_array['address'];
            $receive_prize_obj->identityCard = $arg_array['identityCard'];
            $receive_prize_obj->prize = implode(',', $prize_array);
            $this->dbca->save($receive_prize_obj);

            $this->dbca->commit();

            return array( 'code' => 200, 'message' => '领取成功' );

        } catch ( Exception $e ) {

            $this->dbca->rollBack();

            if ($e->getCode()) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询会员抽奖记录
     * @param $arg_array
     */
    public function searchWxLogInfo(&$arg_array){

        if(!isset($arg_array['promotionID']) || empty($arg_array['promotionID'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        //sql字符串
        $sql = 'WHERE promotionID = ?';

        //参数类型字符串
        $params_type = 'i';

        //参数值数组
        $params_array = array(
            $arg_array['promotionID']
        );

        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND useDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }

        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND useDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        $sql .= ' GROUP BY pcustID,useDate';

        //统计数量
        $search_sql = 'SELECT COUNT(*) AS c_count FROM (
                            SELECT useDate,SUM(T.log_count) AS log_count, COUNT(*) AS cust_count FROM (
                            SELECT COUNT(*) AS log_count ,useDate FROM promotion_weixin_log ' . $sql .'
                            ) AS T GROUP BY T.useDate ORDER BY T.useDate DESC
                        ) AS TT';
        $count_array =& $this->dbca->stmt_query($search_sql, $params_type, $params_array);
        if ($count_array[0]->c_count == 0) {
            return null;
        }
        $arg_array['count'] = $count_array[0]->c_count;

        $search_sql = 'SELECT useDate,SUM(T.log_count) AS log_count, COUNT(*) AS cust_count FROM (
                          SELECT COUNT(*) AS log_count ,useDate FROM promotion_weixin_log ' . $sql .'
                       ) AS T GROUP BY T.useDate ORDER BY T.useDate DESC ';
        $search_sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
        $total_array =& $this->dbca->stmt_query($search_sql, $params_type, $params_array);
        if (!$total_array) {
            return null;
        }

        foreach($total_array as &$count) {

            $search_sql = 'SELECT COUNT(*) AS prize_count FROM promotion_weixin_prize WHERE promotionID = ? AND createTime BETWEEN ? AND ?';
            $prize_count_array =& $this->dbca->stmt_query($search_sql, 'iss', $arg_array['promotionID'], $count->useDate . ' 00:00:00', $count->useDate . ' 23:59:59');

            $item_array[] = array(
                'date' => $count->useDate,
                'log_count' => $count->log_count,
                'cust_count' => $count->cust_count,
                'prize_count' => $prize_count_array[0]->prize_count
            );

        }

        return $item_array;
        return null;

    }

    /**
     * 查询会员中奖纪录
     * @param $arg_array
     * @return array|null
     */
    public function searchWinLogInfo(&$arg_array){

        if(!isset($arg_array['promotionID']) || empty($arg_array['promotionID'])){
            return array('code'=>400,'message'=>'参数错误');
        }

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //会员号
        if (isset($arg_array['pcustID']) && is_numeric($arg_array['pcustID'])) {
            $sql .= ' AND cm.pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        //促销活动ID
        if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID'])) {
            $sql .= ' AND pwp.promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        //时间
        if (isset($arg_array['useDate']) && !empty($arg_array['useDate'])) {
            $sql .= ' AND pwp.useDate = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['useDate'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM promotion_weixin_prize pwp INNER JOIN cust_master cm on pwp.pcustID = cm.pcustID ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询中奖记录信息
            $search_sql = 'SELECT pwp.* FROM promotion_weixin_prize pwp INNER JOIN cust_master cm on pwp.pcustID = cm.pcustID ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'pcustID' => $item->pcustID,                //会员号
                        'promotionID' => $item->promotionID,       //促销活动ID
                        'awardsID' => $item->awardsID,              //奖项ID
                        'awardsName' => $item->awardsName,          //奖项名称
                        'prize' => $item->prize,                     //奖品
                        'isReceive' => $item->isReceive,             //是否已领取奖品
                        'isReceiveName' => $item->isReceive?'是':'否'             //是否已领取奖品
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }

    //微信统计分析
    public function analyseWeixinLog (&$arg_array){
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //创建时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND useDate >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'];
        }
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND useDate <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'];
        }

        if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计数量
                $search_sql = 'SELECT COUNT(DISTINCT useDate) item_count FROM promotion_weixin_log ' . $sql;

                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                $sql_sum = 'SELECT COUNT(DISTINCT pcustID) allNum FROM promotion_weixin_log ' . $sql;
                $count_sum = &$this->dbca->stmt_query($sql_sum, $params_type, $params_array);
                if ($count_sum){
                    $arg_array['allNum'] = $count_sum[0]->allNum;
                }else {
                    $arg_array['allNum'] = 0;
                }

                $sql .= ' GROUP BY useDate ';
                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT COUNT(DISTINCT pcustID) custNum, useDate, promotionID FROM promotion_weixin_log ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'custNum' => $item->custNum,
                    'useDate' => $item->useDate,
                    'promotionID' => $item->promotionID
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    //获奖人数
    public function getPrize (&$arg_array){
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //创建时间
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $sql .= ' AND createTime >= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['startDate'].' 00:00:00';
        }
        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $sql .= ' AND createTime <= ?';
            $params_type .= 's';
            $params_array[] = $arg_array['endDate'].' 23:59:59';
        }

        if (isset($arg_array['promotionID']) && !empty($arg_array['promotionID'])) {
            $sql .= ' AND promotionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['promotionID'];
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            //查询分类信息
            $search_sql = 'SELECT COUNT(DISTINCT pcustID) custNum, promotionID FROM promotion_weixin_prize ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            $item_array = array(
                'custNum' => $temp_item_array[0]->custNum,
                'promotionID' => $temp_item_array[0]->promotionID
            );

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 领奖纪录
     * @param $arg_array
     */
    public function awardRecordList(&$arg_array){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //领奖人手机号码
        if (isset($arg_array['mobile']) && !empty($arg_array['mobile'])) {
            $sql .= ' AND mobile = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['mobile'];
        }

        //领奖日期
        if (isset($arg_array['startDate']) && !empty($arg_array['startDate'])) {
            $startDate = $arg_array['startDate'].' 00:00:00';
            $sql .= ' AND createTime >= ?';
            $params_type .= 's';
            $params_array[] = $startDate;
        }

        if (isset($arg_array['endDate']) && !empty($arg_array['endDate'])) {
            $endDate = $arg_array['endDate'].' 23:59:59';
            $sql .= ' AND createTime <= ?';
            $params_type .= 's';
            $params_array[] = $endDate;
        }

        //领取单ID
        if (isset($arg_array['receive_id']) && !empty($arg_array['receive_id'])) {
            $sql .= ' AND receive_id = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['receive_id'];
        }

        //会员号
        if (isset($arg_array['pcustID']) && !empty($arg_array['pcustID'])) {
            $sql .= ' AND pcustID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['pcustID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4) ;
        }

        try {

            if (isset($arg_array['rp'])) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS num FROM promotion_weixin_receive_prize  ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->num;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询抽奖记录信息
            $search_sql = 'SELECT * FROM promotion_weixin_receive_prize ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array)
                return null;

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {
                    $item_array[] = array(
                        'createTime' => $item->createTime,                //领奖人日期
                        'receive_id' => $item->receive_id,                //领取单ID
                        'pcustID' => $item->pcustID,                      //会员号
                        'custName' => $item->custName,                    //收货人姓名
                        'mobile' => $item->mobile,                        //收货人手机
                        'address' => $item->address,                      //收货地址
                        'identityCard' => $item->identityCard,           //身份证号码
                        'prize' => $item->prize                           //领取的礼品
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 领奖纪录
     * @param $arg_array
     * @return array|null
     */
    public function awardRecordEdit(&$arg_array){

        //实例公共类
        $commHandler = new commHandler();

        /**
         * =================================
         * 检查参数
         * =================================
         */
        if (!isset($arg_array['receive_id'], $arg_array['custName'], $arg_array['a_mobile'], $arg_array['address'], $arg_array['identityCard'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!is_numeric($arg_array['receive_id']) || $arg_array['receive_id'] <= 0) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (empty($arg_array['custName'])) {
            return array( 'code' => 400, 'message' => '收货人不能为空' );
        }
        if (!$commHandler->isMobile($arg_array['a_mobile'])) {
            return array( 'code' => 400, 'message' => '手机号码填写错误，格式：18612345678' );
        }
        if (empty($arg_array['address'])) {
            return array( 'code' => 400, 'message' => '收货地址不能为空' );
        }
        /**
         * =================================
         * 检查参数
         * =================================
         */

        try {

            $receive_prize_obj = new entity('promotion_weixin_receive_prize');
            $receive_prize_obj->receive_id = $arg_array['receive_id'];
            if($this->dbca->fetch($receive_prize_obj)){
                $receive_prize_obj->creator = 'system';
                $receive_prize_obj->custName = $arg_array['custName'];
                $receive_prize_obj->mobile = $arg_array['a_mobile'];
                $receive_prize_obj->address = $arg_array['address'];
                $receive_prize_obj->identityCard = $arg_array['identityCard'];
                $this->dbca->save($receive_prize_obj);
            }else{
                return array( 'code' => 400, 'message' => '不存在该用户' );
            }

            return array( 'code' => 200, 'message' => '领奖纪录保存成功' );

        } catch ( Exception $e ) {

            error_log($e->getMessage());
            return null;

        }
    }

    /**
     * 微信互动活动(保存会员中奖记录数据)
     * @param $arg_array
     */
    public function saveCustomerWxPrize( $arg_array ) {

        $log_obj = new entity('promotion_weixin_prize');
        $log_obj->creator = 'system';
        $log_obj->promotionID = $arg_array['promotionID'];
        $log_obj->pcustID = $arg_array['pcustID'];
        $log_obj->awardsID = $arg_array['awardsID'];
        $log_obj->awardsName = $arg_array['awardsName'];
        $log_obj->prize = $arg_array['prize'];
        $log_obj->prize_num = $arg_array['prize_num'];
        $log_obj->isReceive = 0;
        $this->dbca->save($log_obj);

    }

}


